Why does 'valueAsNumber' return NaN as a value?
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
.
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 type
s that apply to valueAsNumber
. These are:
- Date and Time (
datetime
) (Note thistype=""
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
.