38

I want to return false and return from function if I find first blank textbox

function validate(){
 $('input[type=text]').each(function(){
   if($(this).val() == "")
     return false;
});
}

and above code is not working for me :( can anybody help?

Prashant Lakhlani
  • 5,758
  • 5
  • 25
  • 39

3 Answers3

63

You are jumping out, but from the inner loop, I would instead use a selector for your specific "no value" check, like this:

function validate(){
  if($('input[type=text][value=""]').length) return false;
}

Or, set the result as you go inside the loop, and return that result from the outer loop:

function validate() {
  var valid = true;
  $('input[type=text]').each(function(){
    if($(this).val() == "") //or a more complex check here
      return valid = false;
  });
  return valid;
}
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • @Nick Craver, It is a very old post but I have a question. Is there any risk above that function return `true` before `each` loop completed? – YahyaE Mar 25 '16 at 09:59
  • 1
    Absolutely zero such risk because until .each() completes, it will not proceed to the last statement. @YahyaE –  Jun 29 '16 at 03:39
  • The first example does not work when you need to trim the value first. The second example works, but it relies on a state variable, which is generally fine, but in case you wanted to do pure functional programming it would not be considered valid. – mae Jan 08 '20 at 07:08
18

You can do it like this:

function validate(){
    var rv = true;
    $('input[type=text]').each(function(){
        if($(this).val() == "") {
            rv = false;   // Set flag
            return false; // Stop iterating
        }
    });
    return rv;
}

That assumes you want to return true if you don't find it.

You may find that this is one of those sitautions where you don't want to use each at all:

function validate(){
    var inputs = $('input[type=text]');
    var index;
    while (index = inputs.length - 1; index >= 0; --index) {
        if (inputs[index].value == "") { // Or $(inputs[index]).val() == "" if you prefer
            return false;
        }
    }
    // (Presumably return something here, though you weren't in your example)
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

I want to add something to existing answers to clear the behavior of $(selector).each and why it doesn't respect return false in OP's code.

return keyword inside $(selector).each is used to break or continue the loop. If you use return false, it is equivalent to a break statement inside a for/while loop. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. Source

Because you're returning false, the loop breaks and the function ends up returning undefined in your case. Your option is to use a var outside $.each or avoid using it altogether as @TJCrowder wrote.

Mr.Hunt
  • 4,833
  • 2
  • 22
  • 28