0

In my application, I am taking a value for username. If that value is 0, then I have to run some code. But how should I write the if block?

 var userName=document.getElementById("member").value;

The above statement will return 0 (zero). Can anybody write the if statement for me? Thank you in advance.This is the entire code

var userName=document.getElementById("member").value;
    var password=document.getElementById("password").value;

    if(userName==="0"){
        var div4 = document.getElementById("errorMessage");
        var text1 = "insert userName.";
        div4.style.display = "block";
        div4.style.color = "red";
        div4.style.fontSize = "65%";
        div4.innerHTML = text1;

3 Answers 3

1

Additional to the other answers: you could check for the value 0 this way

if (Number(userName) === 0)

With the advantage that if the user fills the username field with whitespace only (spaces, tabs etc) it will still evaluate to true (that's because the Number conversion trims the parameter value).

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

Comments

0

As the value of userName is of type string, you could use:

if (userName === "0") {
  ...
}

Comments

0

The .value attribute will return a string.

In this case, you can compare the value of userName to 0, the string:

if (userName == '0') {
  ...
}

3 Comments

yes I am aware about this, and this should work for sure.but unexpectedly its not working.I have edited the question a bit.Look if you can find out any mistakes.
What's the error? The code you posted seems fine. Post the HTML as well.
Well it is working now, but for this if(userName=="0"). Intially it wasnt working maybe because I hadnt cleared cache.

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.