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"> </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>
NaN , which stands for "Not a Number", is a value that JavaScript returns from certain functions and operations when the result should be a number, but the result is not defined or not representable as a number. For example: parseInt() returns NaN if parsing failed: parseInt('bad', 10) Math.
A NaN is never equal to itself, by definition. It works this way in any language.
The valueAsNumber provides the value of an input[type=number] as a Number type, instead of the traditional string representation when you get the value: /* Assuming an <input type="number" value="1.234" /> */ // BAD: Get the value and convert the number input.
In JavaScript, NaN is a number that is not a legal number. The Number. isNaN() method returns true if the value is NaN , and the type is a Number.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With