How to break out of jQuery each Loop
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;
}
});
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.
I created a Fiddle for the answer to this question because the accepted answer is incorrect plus this is the first StackOverflow thread returned from Google regarding this question.
To break out of a $.each you must use return false;
Here is a Fiddle proving it:
http://jsfiddle.net/9XqRy/