Vishnu
Vishnu

Reputation: 2452

Break function from inside jquery foreach

I have a simple function like below

function funk()
{
    $.each(game, function(i, curr) {
        check = curr["value"];
        if(check=="") {
            alert("Please Fill");
            return false;
        }

    });
    alert("success");
    return false;

}

So basically when Function funk is called , When check is null , I want to alert and exit from the function.But I have strange problem where , After $.each , alert("succes") too is called;

Upvotes: 1

Views: 290

Answers (1)

Dave
Dave

Reputation: 10924

Just because you break out of the each() loop by returning false, doesn't mean it's going to break out of the wrapping function.

You're going to have to set a variable so you know when your each() loop was intentionally terminated early:

function funk() {
  var broke = false;
  $.each(game, function(i, curr) {
    check = curr["value"];
    if(check=="") {
      alert("Please Fill");
      broke = true;
      return false;
    }
  });

  if (!broke)
    alert("success");

  return false;
}

Upvotes: 2

Related Questions