244

In my application i am using AJAX call. I want to use break and continue in this jQuery loop.

$('.submit').filter(':checked').each(function() {

});
informatik01
  • 15,636
  • 10
  • 72
  • 102
Ravi Kant
  • 4,579
  • 2
  • 23
  • 23
  • possible duplicate of [How to skip to next iteration in jQuery.each() util?](http://stackoverflow.com/questions/481601/how-to-skip-to-next-iteration-in-jquery-each-util) – T J Aug 20 '14 at 14:34
  • Answer can be found here: http://stackoverflow.com/questions/481601/how-to-skip-to-next-iteration-in-jquery-each-util – Buchannon Nov 30 '14 at 02:31

4 Answers4

521

We can break both a $(selector).each() loop and a $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

return false; // this is equivalent of 'break' for jQuery loop

return;       // this is equivalent of 'continue' for jQuery loop

Note that $(selector).each() and $.each() are different functions.

References:

informatik01
  • 15,636
  • 10
  • 72
  • 102
Jayram
  • 17,790
  • 6
  • 49
  • 68
45
$('.submit').filter(':checked').each(function() {
    //This is same as 'continue'
    if(something){
        return true;
    }
    //This is same as 'break'
    if(something){
        return false;
    }
});
  • 3
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Ajean May 12 '16 at 16:08
9

return or return false are not the same as continue. If the loop is inside a function the remainder of the function will not execute as you would expect with a true "continue".

Billy
  • 738
  • 1
  • 7
  • 17
7

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. -- jQuery.each() | jQuery API Documentation

Nabil Kadimi
  • 9,428
  • 2
  • 49
  • 56