Tip: You can get the value of an input element as a number

JavaScript, Browser, Input · Jun 12, 2021

Most of the time, when accessing the value of an HTMLInputElement in an event listener, we use something along the lines of e.target.value. This is fine in most cases, but when we want the numeric value of an input field, we have to parse it and check if the value is actually valid etc. That can get very annoying, especially when working with larger forms that have many input fields.

What if I told you there's an easier way to get the numeric value from an input field? Meet HTMLInputElement.valueAsNumber, a handy attribute that will return a numeric value if the input field's value can be converted to a number or NaN if the conversion is not possible.

const quantityInput = document.getElementById('quantity-input');
let quantity;
// Bad: parseFloat() converts the string to a number
quantity = parseFloat(quantityInput.value);
// Good: returns a numeric value
quantity = quantityInput.valueAsNumber;

As usual, this comes with a caveat which is that it only works for type="number" inputs (although that's probably where you need it the most). On a side note, you can also use HTMLInputElement.valueAsDate to get a Date object from a type="date" input, which might also come in handy in some cases.

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Tips & Tricks

    A collection of quick tips and tricks to level up your coding skills one step at a time.

    Collection · 53 snippets

  • Get elements bigger than viewport

    Returns an array of HTML elements whose width is larger than that of the viewport's.

    JavaScript, Browser · Oct 22, 2020

  • Vertical offset of element

    Finds the distance from a given element to the top of the document.

    JavaScript, Browser · Jan 5, 2021

  • Add multiple listeners

    Adds multiple event listeners with the same handler to an element.

    JavaScript, Browser · Oct 22, 2020