开发者

jQuery if multiple objects equal same value

I have multple objects. Before submitting a form, I want to check to be sure all of the object values are "ok开发者_开发知识库".

$("#sub_button").click(function() {
    if (myObj.login_id && myObj.email == "ok")  {
        alert("This would submit the form. login ID obj is: "+myObj.login_id+" and email email obj is: "+myObj.email);
    } else {
        alert("the form is bad!");
    }
});

I've tried it with two == and three ===, it still isn't working. The myObj.login_id or myObj.email could equal ANYTHING and it still pops up the "This would submit the form" alert, and shows in the alert box that the value(s) is NOT "ok".

What am I doing wrong?


This isn't comparing what you think it's comparing. When you read this aloud, it sounds right: "if login ID and email are equal to OK", but that's not how the && works. You want:

if (myObj.login_id == "ok" && myObj.email == "ok") {
   ....
}

The code you did write actually says "if login ID is anything at all, and if email is "ok" ".


$("#sub_button").click(function() {
    if (myObj.login_id == "ok" && myObj.email == "ok")  {
        alert("This would submit the form. login ID obj is: "+myObj.login_id+" and email email obj is: "+myObj.email);
    } else {
        alert("the form is bad!");
    }
});


You should do:

("#sub_button").click(function() {

    if (myObj.login_id === "ok" && myObj.email === "ok")  {

        alert("This would submit the form. login ID obj is: "+myObj.login_id+" and email email obj is: "+myObj.email);
else {

        alert("the form is bad!");

In your code you just check that myObj.login_id resolves to true (which happens everytime myObj.login_id value is not in this list)

  • false
  • null
  • undefined
  • The empty string ''
  • The number 0
  • The number NaN (yep, 'Not a Number' is a number, it is a special number)


Try this

$("#sub_button").click(function() {

    if (myObj.login_id == "ok" && myObj.email == "ok")  {

        alert("This would submit the form. login ID obj is: "+myObj.login_id+" and email email obj is: "+myObj.email);

    } else {

        alert("the form is bad!");


(myObj.login_id && myObj.email == "ok") will evaluate to true if myObj.email == "ok" and myObj.login_id has a non-zero value. You're not evaluating the contents of login_id to anything, so it'll be handled as a boolean and converted to such according to the contents.

You should change it to (myObj.login_id == "ok" && myObj.email == "ok").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜