Javascript, isNaN and parsing

A word of warning with javascript and the magic of the isNaN function

If we have an element such as

<input type="hidden" id="myelement" value="(some optional value)" />

Then if myelement has a value of "1"

<input type="hidden" id="myelement" value="1" />

var stringToTest = $("#myelement").val();
// stringToTest is "1"
isNaN(stringToTest); // outputs false

If we use a text value such as "test" then we get the following

<input type="hidden" id="myelement" value="test" />

var stringToTest = $("#myelement").val();
// stringToTest is "test"
isNaN(stringToTest); // outputs true

So far, this is all as we would expect. But if we have an empty value attribute like

<input type="hidden" id="myelement" value="" />

then we get the following problem


var stringToTest = $("#myelement").val();
// stringToTest is ""
isNaN(stringToTest); // outputs false!

The isNaN function will return false for an empty string.
An easy solution is if you are expecting a number, make sure it is a number.


var stringToTest = "";

var stringAsInt = parseInt(stringToTest); // outputs NaN

isNaN(stringAsInt); // outputs true, as we would expect

Share Tweet Send
0 Comments
Loading...
You've successfully subscribed to SimonReynolds.ie
Great! Next, complete checkout for full access to SimonReynolds.ie
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.