Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access this variable outside of this jquery loop?

I have a simple jquery loop that goes through my form and

  1. sees if there is empty fields.
  2. If any are empty, mark them with an 'empty' class and
  3. then create a 'error' variable

Basically:

// check all the inputs have a value...
$('input').each(function() {

    if($(this).val() == '') {

        $(this).addClass('empty');
        var error = 1;

    }   

});

This works a charm. However, as my code continues, I can't seem to access that 'error' variable... as though it is locked inside the each loop. With the following code being right after the .each() loop, I never get my_error_function() to fire, even though I know that criteria 1 and 2 are working.

if(error == 1) {

    my_error_function();

} else {

    my_non_error_function();

}

How do I access this variable so I can use its result elsewhere in the code?

like image 780
willdanceforfun Avatar asked Dec 09 '22 09:12

willdanceforfun


1 Answers

Define your error variable outside of your function/loop

var error = 0;
$('input').each(function() {

    if($(this).val() == '') {

        $(this).addClass('empty');
        error = 1;

    }   

});
like image 83
Arthur Halma Avatar answered Dec 14 '22 23:12

Arthur Halma