Working with HTML inputs may require handling proper value types, like numbers. However, the
value property of an input element will return a string-type value by default.
In this article I’m going to explain how you can get the numeric value from the input field. It is important to work with correct value types when parsing user input, otherwise it can produce bugs and unwanted behaviour.
Given the input with a
number let’s get its value.
<input type="number" value="42">
By default, the
value property of the input element will always return a
string type, even if the input
type is a
const numberInput = document.querySelector("input[type=number]") numberInput.value // "42"
💡 NOTE: the
type attribute of the
input element can be equal to a many different values, but its
value property will always return a string-type value
To get the
number type value from the input element you can use one of two approaches.
const numberInput = document.querySelector("input[type=number]") parseInt(numberInput.value) // 42
This approach is useful when working with input types like
search, as the user may input a numeric value, and you may want to capture that.
If the input value is not a number the
parseFloat will return a
parseFloat methods works in all browsers.
The second approach is to use the
valueAsNumber property instead of the
value property on an input element.
const numberInput = document.querySelector("input[type=number]") numberInput.valueAsNumber // 42
valueAsNumber property will always work on input types like:
week. But if you use this property say on a
text type input it will return a
This is a more straightforward approach especially if you know the input
type you’re working with.
valueAsNumber property is supported in all browsers as well.