Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a integer value from a textbox, how to check if it's NaN or null etc?

I am pulling a value via JavaScript from a textbox. If the textbox is empty, it returns NaN. I want to return an empty string if it's null, empty, etc.

What check do I do? if(NAN = tb.value)?

like image 622
Blankman Avatar asked Apr 27 '09 13:04

Blankman


2 Answers

Hm, something is fishy here.

In what browser does an empty textbox return NaN? I've never seen that happen, and I cannot reproduce it.

The value of a text box is, in fact a string. An empty text box returns an empty string!

Oh, and to check if something is NaN, you should use:

if (isNaN(tb.value))
{
   ...
}

Note: The isNaN()-function returns true for anything that cannot be parsed as a number, except for empty strings. That means it's a good check for numeric input (much easier than regexes):

if (tb.value != "" && !isNaN(tb.value))
{
   // It's a number
   numValue = parseFloat(tb.value);
}
like image 182
Tor Haugen Avatar answered Oct 02 '22 00:10

Tor Haugen


You can also do it this way:

var number = +input.value;
if (input.value === "" || number != number)
{
    // not a number
}

NaN is equal to nothing, not even itself.

if you don't like to use + to convert from String to Number, use the normal parseInt, but remember to always give a base

var number = parseInt(input.value, 10)

otherwise "08" becomes 0 because Javascript thinks it's an octal number.

like image 27
fforw Avatar answered Oct 02 '22 01:10

fforw