3

Possible Duplicate:
How to break/exit from a each() function in JQuery?

I want to exit the jQuery .each loop on some condition, How can I do it. Will exit; code work?

var r = true; 
$('.hour').each(function() {
   var $hours =  $(this).val();
   if ($hours == "") {
     alert(" Active Time is required"); 
     r = false; 
     //exit;         
   }    
}); 
return r; 
Community
  • 1
  • 1
Mansoor
  • 130
  • 1
  • 11

3 Answers3

7

You should use return false:

$(".hour").each(function() {
    if (want_to_break) {
        return false;
    }
});
VisioN
  • 143,310
  • 32
  • 282
  • 281
3

Use break; to break out of a conventional loop, whereas with this jQuery each function I suggest you return; or return false;.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
1
.each(function() {
    if (iWantToBreak)
        return false;
});

Repost of the following:

How to break/exit from a each() function in JQuery?

Community
  • 1
  • 1
msj121
  • 2,812
  • 3
  • 28
  • 55