1

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?

0

5 Answers 5

4

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" ".

Sign up to request clarification or add additional context in comments.

Comments

2
$("#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!");
    }
});

Comments

1

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)

1 Comment

I can't believe I didnt catch that. Thank you!
0

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!");

Comments

0

(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").

Comments

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.