281

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

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

});
2

4 Answers 4

607

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:

Sign up to request clarification or add additional context in comments.

4 Comments

Although true, this doesn't seem to be documented. Is this an 'unofficial' feature?
It is documented here api.jquery.com/jquery.each @MichaelScheper
That's the first place I looked, of course. I see it now; it kinda gets lost amongst all the examples.
return true; is also equivalent to continue.
56
$('.submit').filter(':checked').each(function() {
    //This is same as 'continue'
    if(something){
        return true;
    }
    //This is same as 'break'
    if(something){
        return false;
    }
});

Comments

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".

Comments

8

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.