Why does 'valueAsNumber' return NaN as a value?

后端 未结 2 1356
日久生厌
日久生厌 2020-12-11 00:59

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?

相关标签:
2条回答
  • 2020-12-11 02:06

    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.

    0 讨论(0)
  • 2020-12-11 02:06

    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.

    0 讨论(0)
提交回复
热议问题