Why does "valueAsNumber" return NaN as a value?

In the code below, I'm trying to call valueAsNumber , but I will just go back to NaN. When I use parseInt , I get the expected result. 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> 
+6
source share
2 answers

Your expectations are reasonable given the name of the property, but when reading the actual specifications / documentation :

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

On receipt, if the valueAsNumber attribute is not applied, as defined for the current state of the input element type attribute, then return a Not-a-Number (NaN) value.

Here is a table listing the valueAsNumber that are related to valueAsNumber . It:

Date and time,
The date,
Month,
A week,
Time
Local date and time
room
Range

Yes, this is a rather weird API solution.

+10
source

You must set the type your input to number :

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

In addition, if the value is empty or non-numeric, it will return NaN .

+3
source

Source: https://habr.com/ru/post/951044/


All Articles