Norse
Norse

Reputation: 5757

JQuery end $.each() loop inside of $.click

$('#button').click(function() {
   $('.field').each(function() {
      if (condition) {
         return false;
      }
   });
   alert("This alerts even when loop returns false");
});

If my if condition reaches return false; the script will continue to move through the $.click event. Is it possible to completely stop all javascript functions/events?

Upvotes: 4

Views: 1220

Answers (1)

nbrooks
nbrooks

Reputation: 18233

That return ends the inner function block; to end the outer block, use another return:

$('#button').click(function() {
    var exit = false;
    $('.field').each(function() {
        if (condition) {
            exit = true;
            return false;
        }
    });

    if( exit ) {
        return false;
    }

    alert("This alerts even when loop returns false");
});

(Alternatively you could conditionally execute the remaining code based on a boolean variable that you set, similar to how I set exit)

Upvotes: 3

Related Questions