0

I have used return false to terminate each loop but it is not breaking the loop. My code is as below :

$.each(popuparray, function (i, item) {
    $('.droparea >.ss-active-child').each(function () {
        if (this.id == finaldivId) {
            alert("this is " + this.id + "  finaldivId  " + finaldivId);
            return false;
        }
    });
    //some code here as well
});

Kindly suggest me the solution.

3
  • 1
    you want both loops to exit? Commented May 28, 2014 at 10:08
  • Yes I want to exit both loop. Commented May 28, 2014 at 10:09
  • see my answer hope it helps Commented May 28, 2014 at 10:10

3 Answers 3

3

Try to declare one flag and switch it based on the internal loop's flow and based on that flag decide the outer loop's flow,

var xCondition = false;

$.each(popuparray, function (i, item) {
    $('.droparea >.ss-active-child').each(function () {
        if (this.id == finaldivId) {
            alert("this is " + this.id + "  finaldivId  " + finaldivId);
            xCondition = true;
            return false;
        }
    });

    if(xCondition){ xCondition = false; return false; }   
});
Sign up to request clarification or add additional context in comments.

Comments

0

You need to return from the out loop also, you can use a flag variable to keep track of the valid state in the inner loop, and return its value from the outer one.

$.each(popuparray, function (i, item) {
    var flag = true;
    $('.droparea >.ss-active-child').each(function () {
        if (this.id == finaldivId) {
            alert("this is " + this.id + "  finaldivId  " + finaldivId);
            flag = false;
            return false;
        }
    });
    //some code here as well
    return flag;
});

Comments

0

If you want both loop to exit on condition then do like this:

$.each(popuparray, function (i, item) {
    var flag = true;
    $('.droparea >.ss-active-child').each(function () {
        if (this.id == finaldivId) {
            alert("this is " + this.id + "  finaldivId  " + finaldivId);
            flag = false;
            return false;
        }
    });
if(!flag)
{
  return false;
}   

});

Note: return true acts as continue so you need to check the flag and then return false in outer loop.

1 Comment

Note return true will act as continue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.