Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of jQuery each loop?

How do I break out of a jQuery each loop?

I have tried:

 return false; 

in the loop but this did not work. Any ideas?


Update 9/5/2020

I put the return false; in the wrong place. When I put it inside the loop everything worked.

like image 719
Luke101 Avatar asked Nov 23 '09 17:11

Luke101


People also ask

How do I get out of each loop in jQuery?

You can stop the loop from within the callback function by returning false . $( this ). addClass( "foo" ); });

How do you break exit each loop?

We can break the $. each() loop [..] by making the callback function return false. BTW, continue works like this: Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

How do you exit each function?

each(function() { // Code // To escape from this block based on a condition: if (something) return false; }); From the documentation of the each method: Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop).

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.


2 Answers

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.

$.each(array, function(key, value) {      if(value === "foo") {         return false; // breaks     } });  // or  $(selector).each(function() {   if (condition) {     return false;   } }); 
like image 90
Christian C. Salvadó Avatar answered Oct 06 '22 10:10

Christian C. Salvadó


According to the documentation return false; should do the job.

We can break the $.each() loop [..] by making the callback function return false.

Return false in the callback:

function callback(indexInArray, valueOfElement) {   var booleanKeepGoing;    this; // == valueOfElement (casted to Object)    return booleanKeepGoing; // optional, unless false                             // and want to stop looping } 

BTW, continue works like this:

Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

like image 33
powtac Avatar answered Oct 06 '22 11:10

powtac