3

I have an onclick even set up to take the value of an input and alert if the value is a number. If the value of the input is blank, I am trying to alert it to say "No Number," however, it seems that even if my input it empty the function returns a statement saying the the "empty" value is indeed a number.

I have set variable up to parse the value of the input right away, but is this why my code is always returning "Is a number," because it's automatically set to be one when it collects the variable?

Code:

HTML:

<input type="text" id="numberTest" />

<button id="button">Click Me</button>

JS:

var button = document.getElementById("button");

button.onclick = function()
{
var numberTest = parseInt(document.getElementById("numberTest").value);

if(numberTest == NaN || "" || null)
{
    alert("No Number");
}
else
{
    alert("This is a number!");
}
};
Theodore Steiner
  • 1,553
  • 2
  • 23
  • 34
  • Possible duplicate of [Is there any function like IsNumeric in javascript to validate numbers](http://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers) – Liam Aug 24 '16 at 13:08
  • The duplicate of that is probably better actually [Validate decimal numbers in JavaScript - IsNumeric()](http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric) – Liam Aug 24 '16 at 13:09
  • Thanks Liam, I'll check it out! – Theodore Steiner Aug 24 '16 at 13:24

3 Answers3

8

Checking if == NaN will always return false. The proper way to do this is with Number.isNaN():

var button = document.getElementById("button");

button.onclick = function() {
    var numberTest = parseInt(document.getElementById("numberTest").value);
    if (Number.isNaN(numberTest) || numberTest == "" || numberTest === null) {
        alert("No Number");
    }
    else {
        alert("This is a number!");
    }
};

You also had some issues with your logic in the if - each clause is a separate expression, and therefore needs to check against numberTest every time.

Scott
  • 5,338
  • 5
  • 45
  • 70
3

Try using isNaN() method:

isNaN(numberTest)

instead of

numberTest == NaN

According to NaN documentation, NaN is never equal NaN, so NaN == NaN or NaN === NaN will always return false...

BTW, you should change that:

if(numberTest == NaN || "" || null)

to this:

if(isNaN(numberTest) || numberTest == "" || numberTest == null)

so you always compare your variable to a value.

Alan Jurczak
  • 479
  • 5
  • 14
2

This is another way to know if value is number or not

function IsANumber(numberToValidate) {
   return $.isNumeric(numberToValidate.replace(",", "").replace(".", ""));
} 
$("[id^=YourIDButton]").click(function(){
    if(IsANumber($(this).val())){
       alert("This is a number!");
    }else{
       alert("No number");
    }
}
Monicalh
  • 101
  • 1
  • 5