JavaScript Tip: How to Quickly Extract Number Inputs
Use valueAsNumber
Using the value
property is the most common way of getting the value of an input element. This property always returns a string, even when the input value is a number. As a result, when processing a number form field, we often have to use parseInt()
or parseFloat()
to convert the resulting string into a number. Consider this example:
<input type="number" value="30" id="numberinput">
let input = document.querySelector('#numberinput').value;
console.log(typeof input); // => stringinput = parseFloat(input, 10);
console.log(typeof input); // => number
Not many developers know that input elements with type="number"
have an additional property that we can take advantage of to cut the parseInt()
/parseFloat()
step: valueAsNumber
.
Here’s an example:
// notice the valueAsNumber at the end of the statement
let input = document.querySelector('#numberinput').valueAsNumber;console.log(typeof input); // => number
Here, we’ve replaced value
with valueAsNumber
resulting in a number type. Keep in mind that if the input is empty, valueAsNumber
will return NaN
, as opposed to an empty string.
The takeaway from this short post is that when you want to store user input as a number, for example when you have a form that collects years employed or number of dependents, opt for valueAsNumber
rather than value
.
Where else do you think valueAsNumber
would come in handy? Let us know in the comments.
If you enjoyed this article, you may also like Faraz Kelhini’s book, Modern Asynchronous JavaScript. Through August 15, 2022, you can use promo code fkajs_medium_35 to save 35% on the ebook version. Promo codes are not valid on prior purchases.