Input value is a string instead of a number
Solution 1:
Check out HTMLInputElement.valueAsNumber
:
The value of the element, interpreted as one of the following in order:
- a time value
- a number
- null if conversion is not possible
var testInput = document.getElementById("test-input");
function handleInput(e){
var value = this.valueAsNumber;
console.log("type: %s, value: %o", typeof value, value);
}
testInput.addEventListener("input", handleInput);
handleInput.call(testInput);
<input type="number" id="test-input" type="number" value=5>
This will return NaN
for non-numerics or non-finite numbers.
Solution 2:
HTMLInputElement.prototype.value
(for <input>
elements) is a string.
Convert your numeric string to a proper number using one of these:
parseInt(value, 10); // Parsing string as integer (whole number) from left to right.
parseFloat(value); // Parsing string as floating point number (decimal) from left to right.
Number(value); // Converting entire string to number.
JSBin demo.
Alternatively, add a unary +
before the value:
+value; // Equivalent to `Number(value)`.
To be totally sure your value
is a number, you can also do:
if(!isNaN(parseFloat(el.value)) && isFinite(el.value)){
// true if element’s value is a number (or a number in string)
}
For example:
var uw = document.getElementById("wakken");
var ui = document.getElementById("ijsberen");
var up = document.getElementById("penguins");
// Log strings
console.log(uw.value); // "5"
console.log(ui.value); // "5"
console.log(up.value); // "0"
// Log numbers
console.log(Number(uw.value)); // 5
console.log(+uw.value); // 5
console.log(parseInt(ui.value, 10)); // 5
console.log(parseFloat(up.value)); // 0
Don’t forget to read the documentation:
parseInt
parseFloat
Number
- Unary
+
Solution 3:
You can convert the value from string to number using parseFloat(value)
for decimals or parseInt(value)
for integers.
For example:
// uw will refer to the numerical value of the element with id = wakken
var uw = parseInt(document.getElementById("wakken").value);