I am writing a HTML form that does some simple calculation if the input is a number. However, my number input is not being regarded by the javascript function as a number. I am confused why this is so and did some testing with jsFiddle using the following code
HTML
<form>
<input name=a type=number value='' oninput='checka();'>
<input name=b type=number value='' oninput='checkb(this);'>
</form>
Javascript
function checka() {
alert(isNaN(document.forms[0].a.value));
}
function checkb(A) {
alert(isNaN(this.value));
}
I am dumbfounded by the result. The checka
function works normally giving false when '5' is entered and true when 'a' is entered. However, the checkb
function gives true for both cases.
I understand from Mozilla documentation that isNaN
function may do type conversion first before checking the input whether it is a number or not:
Confusing special-case behavior
Since the very earliest versions of the isNaN function specification, its behavior for non-numeric arguments has been confusing. When the argument to the isNaN function is not a number, the value is first coerced to a number. The resulting value is then tested to determine whether it is NaN. Thus for non-numbers that when coerced to numeric type result in a valid non-NaN numeric value (notably the empty string and boolean primitives, which when coerced give numeric values zero or one), the "false" returned value may be unexpected; the empty string, for example, is surely "not a number." The confusion stems from the fact that the term, "not a number", has a specific meaning for numbers represented as IEEE-794 floating-point values. The function should be interpreted as answering the question, "is this value, when coerced to a numeric value, an IEEE-794 'Not A Number' value?"
How does this help to explain the phenomenon that I am seeing? Or is this another form of confusion not related to type conversion?