Sebastien
Sebastien

Reputation: 250

Stop jquery each loop

How can i stop $.each loop?

$.each(files, function(index, file){
    if(file.field_index == remove_file_index){
        //Find remove_file_index Stop $.each
    }
});

Continue to execute code...     

Thanks

Upvotes: 2

Views: 6022

Answers (2)

user632287
user632287

Reputation:

Here's a fiddle demonstrating breaking out of the loop: http://jsfiddle.net/9XqRy/

// Array
var bar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Generic function
function loopTest(exit) {
    // jQuery each
    $.each(bar, function (i, o) {
        // Append result to foo div
        $("#foo").append(o + "<br />");
        // If exit is passed, and i is 4, return false
        if (exit && i == 4) {
            return false;
        }
    });
}

// Without exit
loopTest();

// Create a seperator for visual
 $("#foo").append("<br />---<br /><br />");

// With exit
loopTest(true);

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can return false to stop the loop

Upvotes: 12

Related Questions