Skip to content Skip to sidebar Skip to footer

Why Does 'valueasnumber' Return Nan As A Value?

In the code below, I am trying to call valueAsNumber but I just get a NaN returned. When I use parseInt I get the result I expect. Why Is this?

Solution 1:

Your expectations are reasonable considering the property name, but reading actual specs/documentation:

The valueAsNumber IDL attribute represents the value of the element, interpreted as a number.

On getting, if the valueAsNumber attribute does not apply, as defined for the input element's type attribute's current state, then return a Not-a-Number (NaN) value.

Here's a table that list's types that apply to valueAsNumber. These are:

  • Date and Time (datetime) (Note this type="" is now obsolete in HTML LS)
  • Date (date)
  • Month (month)
  • Week (week)
  • Time (time)
  • Local Date and Time (datetime-local)
  • Number (number)
  • Range (range)

Observe that type="text" is conspicuously absent from the above list, therefore textInput.valueAsNumber will always return NaN even when isNaN( parseInt( textInput.value, 10 ) ) === false.

Solution 2:

You have to set the type of your input to number:

<input name="number1"type="number">

Also, if the value is empty or non-numeric, it'll return NaN.

Solution 3:

I fixed with a cast:

var nOP = Number(document.getElementById("hidNED").value);

In my case only possible contents of hidNED were 0, 1, 2, 3. I am pretty new to javascript and was not aware of valueAsNumber but may well have tried it if I had been.

Post a Comment for "Why Does 'valueasnumber' Return Nan As A Value?"