skip to Main Content

I want to get Laravel validation error count value into the javascript variable and notify to the user to you have missout the required number to the user using sweet alert. how does the pass error count to js variable?

{{ $errors->count() }}

this error count needs to pass the js variable.laravel errors will generate after the submission .how do i get this value using JS or Jquery.i try following way it not work to me.

$("#btn-submit").click(function(event) {
    var error_count = "<?php echo $errors->count(); ?>";
    alert(error_count);

});

2

Answers


  1. the tag can’t compile blade templating syntax. Instead of using blade

    {{ $errors->count() }} 
    

    you can try with php tags with echo and htmlspecialchars

    <?php echo htmlspecialchars($errors->count()) ?>
    

    Try:

    var error_count =  <?php echo htmlspecialchars($errors->count()) ?>;
    
    Login or Signup to reply.
  2. Note: $errors->count() works/activate after you submit the form request. If you need to get the count afterwards, you can do it like this

    @if($errors->count())
        <script>
            alert( {{$errors->count()}} );
        </script>
    @endif
    

    If you wish to show the error count before submitting, you might have to AJAX or some frontend validation javascript libraries

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search