This content originally appeared on Go Make Things and was authored by Go Make Things
Today, we’re going to look at how to get the value of an input element as a number using vanilla JS.
We’ll look at the traditional way of doing that, and an awesome modern property that makes it even easier. Let’s dig in!
An example
Let’s imagine you have an input element with a type of number.
<label for="num">Pick a number</label>
<input type="number" id="num" value="0">Whenever the user updates the value of the field, you want to get the value of the num field as a number.
let num = document.querySelector('#num');
// Handle number changes
num.addEventListener('input', function () {
// ...
});
Let’s look at two ways you can do that.
Convert the value property string to a number
The num.value property returns a string, even when the field type is number.
We can use a number-to-string method, like parseInt() or parseFloat(), to convert the num.value into a number.
// Handle number changes
num.addEventListener('input', function () {
// As a string
let val = num.value;
// As a number
let valAsNumber = parseFloat(num.value);
});
Use the valueAsNumber property
As a modern alternative, you can use the HTMLInputElement.valueAsNumber property (I just learned this trick from Steve Sewell).
As its name implies, it returns the value of an input element as a number instead of a string.
// Handle number changes
num.addEventListener('input', function () {
// As a number
let val = num.valueAsNumber;
});
This works in all modern browsers. Here’s another demo.
⏰ Last Chance! A new session of the Vanilla JS Academy started this week, but it's not too late to join. Sign up today and get 25% off registration.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2022-04-05T14:30:00+00:00) How to get the value of an input as a number with vanilla JavaScript. Retrieved from https://www.scien.cx/2022/04/05/how-to-get-the-value-of-an-input-as-a-number-with-vanilla-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.