Why does 'valueAsNumber' return NaN as a value?

javascript, type-conversion

Solution

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 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`.

Problem

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? ``` <html> <head> <title>JavaScript: Demo 1</title> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body> <div id="numbers"> <div id="inputs"> <form name="inputForm"> <div class="prompt">Number 1: <input name="number1" type="text"></div> <div class="prompt">Number 2: <input name="number2" type="text"></div> </form> </div> <div id="result"> <div class="prompt">RESULT: <span id="operation_result">&nbsp;</span></div> </div> </div> <div id="operations"> <p><a id="add_link" href="#" onClick="add(this)">ADD</a></p> </div> <script type="text/javascript"> function add(linkElement){ // var value1 = parseInt(document.inputForm.number1.value); // var value2 = parseInt(document.inputForm.number2.value); var value1 = document.inputForm.number1.valueAsNumber; var value2 = document.inputForm.number2.valueAsNumber; var result = value1 + value1; document.getElementById('operation_result').innerHTML = result; } </script> </body> </html> ```

Original source

Related problems