david
david

Reputation: 33517

How do I break out of an $.each in jquery?

How to I break out of the following jquery each method when a condition is met;

var rainbow = {'first' : 'red', 'second' : 'orange', 'third' : 'yellow'};

$.each(rainbow, function (key, color) {

  if (color == 'red') {

    //do something and then break out of the each method
    alert("i'm read, now break.");

  }

});

Upvotes: 2

Views: 639

Answers (6)

Mukesh Yadav
Mukesh Yadav

Reputation: 2386

We can not use Break and Continue in jquery functions
Try this

var rainbow = {'first' : 'red', 'second' : 'orange', 'third' : 'yellow'};

$.each(rainbow, function (key, color) {

  if (color == 'red') {
    //do something and then break out of the each method
    alert("i'm read, now break.");
    return false;
  }
  alert(color);
});

Upvotes: 1

zod
zod

Reputation: 12417

<script>
    var arr = [ "one", "two", "three", "four", "five" ];

    jQuery.each(arr, function() {
      $("#" + this).text("Mine is " + this + ".");
       return (this != "three"); // will stop running after "three"
   });


</script>

Try this

http://api.jquery.com/jQuery.each/

Upvotes: 1

Spudley
Spudley

Reputation: 168655

The JQuery documentation for each states:

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.

It also provides examples.

Upvotes: 1

Diego
Diego

Reputation: 16714

var rainbow = {'first' : 'red', 'second' : 'orange', 'third' : 'yellow'};

$.each(rainbow, function (key, color) {

  if (color == 'red') {

    //do something and then break out of the each method
    alert("i'm read, now break.");

    return false;

  }

});

Upvotes: 3

tsimbalar
tsimbalar

Reputation: 5990

As explicitly written on jQuery's page for $.each :

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.

Please google the terms you search before posting here ! It's a pity that jQuery has one of the best documentations ever if you do not bother to read about it !

Upvotes: 2

Related Questions