Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a value when using jQuery.each()?

Tags:

jquery

each

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?

like image 439
Prashant Lakhlani Avatar asked Sep 29 '10 09:09

Prashant Lakhlani


People also ask

What is the use of jQuery each () function?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

Can jQuery return value?

Projects In JavaScript & JQueryYou cannot return variable value from jQuery event function.

Can we use foreach in jQuery?

each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.

How do I get out of each loop in jQuery?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.


2 Answers

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; } 
like image 145
Nick Craver Avatar answered Sep 28 '22 04:09

Nick Craver


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) } 
like image 32
T.J. Crowder Avatar answered Sep 28 '22 04:09

T.J. Crowder