Skip to main content

HTML input type="numer"

HTML <input type="number"> elements are used to create numeric form inputs. They allow the user to control a numerical value within a range, and provide feedback about the validity of input values. In this article, we'll look at how to use HTML's <input type="number"> element, as well as some code snippets you can use with it. 

Examples

<label for="numberField">Number:</label>
<input type="number" name="numberField" id="someNumberInput" min="1" max="10" />

This creates an <input> element with an initial value of blank and a minimum and maximum number range (in this example, 1-10). If you want to set an initial value, simply add the `value` attribute like so:

<label for="numberField">Number:</label>
<input type="number" name="numberField" id="someNumberInput" min="1" max="10" value="5"/>

Now when you access the input field, it will have an initial value of 5 set. 

 You can also specify small steps for incrementing or decrementing the input field's value by using attributes such as `step`. The following code snippet shows how: 

<label for="numberField">Number:</label>
<input type="number" name="numberField" id="someNumberInput" min="1" max="10" step=".25"/>

By adding the `step` attribute with a decimal point (.25), every time you select up/down arrows (on desktop) or scroll (on mobile devices) it will increase/decrease by .25 increments instead of increasing/decreasing by 1.

Attributes

To set restrictions on the input, you can use the following attributes:

  • max: specifies the highest allowed value
  • min: specifies the lowest allowed value
  • step: sets the legal number intervals
  • value: sets a default value for the field.

Working with JavaScript

Let's take a look at how to get data from this input element in JavaScript.

const ageInput = document.getElementById('age-input');
const age = ageInput.valueAsNumber;
ageInput.min = 1;
ageInput.max = 150;
ageInput.step = 1;
const numberInput = document.querySelector('input[type="number"]');
const minValue = 0;
const maxValue = 100;
if (numberInput.value < minValue || numberInput.value > maxValue) {
  // display an error message
  console.log('Value must be between ' + minValue + ' and ' + maxValue);
}
const numberInput = document.querySelector('input[type="number"]');
numberInput.addEventListener('change', (event) => {
  // do something with the new value
  const newValue = event.target.value;
});