Reputation: 7618
How to break .each loop in JavaScript,
if(badCatsNames.length > 0)
{
for (var i = 0; i < badCatsNames.length; i++) {
var badCatName = badCatsNames[i];
$("[id$=listAvailableCats] li").each(function (index) {
if ($(this).text() == badCatName) {
$(this).appendTo($("[id$=listPurchasingCats]"));
}
else {
$("[id$=listPurchasingCats] li").each(function (index) {
if ($(this).text() == badCatName) {
$(this).appendTo($("[id$=listAvailableCats]"));
}
});
}
});
}
}}
If code finds bad cat name in availabel cats list then break and start again @ for loop
Upvotes: 2
Views: 54
Reputation: 2403
you can use return false; to exit a loop at any time.
if(badCatsNames.length > 0)
{
for (var i = 0; i < badCatsNames.length; i++) {
var badCatName = badCatsNames[i];
$("[id$=listAvailableCats] li").each(function (index) {
if ($(this).text() == badCatName) {
$(this).appendTo($("[id$=listPurchasingCats]"));
}
else {
$("[id$=listPurchasingCats] li").each(function (index) {
if ($(this).text() == badCatName) {
$(this).appendTo($("[id$=listAvailableCats]"));
return false;
}
});
}
});
}
}};
Upvotes: 1
Reputation: 104775
return true;
will skip the current iteration and head to the next, return false;
will leave the each
loop completely.
Upvotes: 6