Return a value when using jQuery.each()?

Viewed 50574

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?

3 Answers

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.

Related