1

This is my script (simplified):

var $error = false;
//Check for errors
$('.required').each(function()
{
    var $error = true;
});
alert($error);

How to make the above code return true in the alert function? The each function is executed 3 times at my page to check for empty fields. But in the above the alert contains false instead of true. Is there a way to parse the variable $error outside the each function to check if there are empty fields after the each loop?

Rens Tillmann
  • 474
  • 2
  • 7
  • 21

5 Answers5

3

You are shadowing the outer $error variable inside the .each() callback. Get rid of the var so you reference the outer one instead:

var $error = false;
$('.required').each(function() {
    $error = true; // Now this refers to the `$error` declared above
});

However, if you're simply using the .each call to check if any elements have the .required class, you could just check .length:

alert($('.required').length > 0); // true or false depending if elements matched
James Allardice
  • 164,175
  • 21
  • 332
  • 312
3

just remove the inner var keyword

var $error = false;
//Check for errors
$('.required').each(function()
{
     $error = true;  // No Var Here
});
alert($error);

or use window as your namespace like the following

window.error = false;
//Check for errors
$('.required').each(function()
{
     window.error = true;  // No Var Here
});
alert(window.error);

Note its better to break the loop if you got an error with return false -- just a performance advice !

Hilmi
  • 3,411
  • 6
  • 27
  • 55
3

Drop the var inside the .each() callback function, otherwise you are defining a new variable in a different scope.

var $error = false;
//Check for errors
$('.required').each(function()  //<-- start of new scope block
{
    var $error = true;  //<--defines new variable -- different from one above
});
alert($error);

Dropping var, it will now use the variable defined in the block above it

var $error = false;
//Check for errors
$('.required').each(function()  
{
    $error = true;  
});
alert($error);
ajp15243
  • 7,704
  • 1
  • 32
  • 38
epascarello
  • 204,599
  • 20
  • 195
  • 236
2

You $erro declared locally and globally

var $error = false;
$('.required').each(function()
{
    $error = true;
});
PSR
  • 39,804
  • 41
  • 111
  • 151
0

If you want to check if the texts are empty you can use:

var $error = false;
$('input.anyclass').each(function()
{
    if($(this).val() == "")
    {
        $error = true;
    }
});
alert($error);