Mathematics
Mathematics

Reputation: 7618

how to break loop in jquery in my code

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]"));
                    }
                });
            }
        });
    } 
}}

What I want

If code finds bad cat name in availabel cats list then break and start again @ for loop

If you can improve code too, please do :)

Upvotes: 2

Views: 54

Answers (2)

JF it
JF it

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

tymeJV
tymeJV

Reputation: 104775

return true; will skip the current iteration and head to the next, return false; will leave the each loop completely.

Upvotes: 6

Related Questions