tags:

views:

81

answers:

6

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

  }

});
+1  A: 

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 !

tsimbalar
Thanks, I did do as you suggested before I posted here. I have dyslexia so sometimes I miss text even when it's right in front of me.
DKinzer
@DKinzer : sorry if my comment sounded violent or rude :-/
tsimbalar
+2  A: 
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;

  }

});
Diego
A: 

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.

Spudley
A: 
<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/

zod
A: 

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);
});
MakDotGNU