Rens Tillmann
Rens Tillmann

Reputation: 474

How to return a variable with jQuery each function

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?

Upvotes: 1

Views: 6000

Answers (5)

epascarello
epascarello

Reputation: 207521

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);

Upvotes: 3

Thiago Dias
Thiago Dias

Reputation: 1

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);

Upvotes: 0

PSR
PSR

Reputation: 40328

You $erro declared locally and globally

var $error = false;
$('.required').each(function()
{
    $error = true;
});

Upvotes: 2

Hilmi
Hilmi

Reputation: 3441

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 !

Upvotes: 3

James Allardice
James Allardice

Reputation: 165991

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

Upvotes: 3

Related Questions