How to access this variable outside of this jquery loop?

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

  • sees if there are empty fields.
  • If they are empty, label them with an “empty” class and
  • then create the variable 'error'

Basically:

// check all the inputs have a value... $('input').each(function() { if($(this).val() == '') { $(this).addClass('empty'); var error = 1; } }); 

It works. However, as my code continues, I cannot access this "error" variable ... as if it was locked inside each loop. When the following code is right after the .each () loop, I never run my_error_function (), although I know that criteria 1 and 2 work.

 if(error == 1) { my_error_function(); } else { my_non_error_function(); } 

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

+4
source share
2 answers

Define your error variable outside of your function / loop

 var error = 0; $('input').each(function() { if($(this).val() == '') { $(this).addClass('empty'); error = 1; } }); 
+12
source

Define a variable outside the scope or assign it to a global variable. name variables also work (e.g. foo.bar.error = 1)

 $('input').each(function() { if($(this).val() == '') { $(this).addClass('empty'); window.error = 1; } }); ... alert(error); 
+2
source

Source: https://habr.com/ru/post/1346694/


All Articles