user1305398
user1305398

Reputation: 3690

verify integer value in javascript

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;

Upvotes: 0

Views: 78

Answers (3)

KooiInc
KooiInc

Reputation: 122986

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

Upvotes: 1

Blender
Blender

Reputation: 298512

The .value attribute will return a string.

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

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

Upvotes: 0

Dan D.
Dan D.

Reputation: 74675

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

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

Upvotes: 0

Related Questions