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?
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:
datetime
) (Note this type=""
is now obsolete in HTML LS)date
)month
)week
)time
)datetime-local
)number
)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
.
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
.