How to avoid decimal values in a number input with JavaScript?

Spread the love

To avoid decimal values in a number input with JavaScript, we use parseInt to convert the value to an integer.

For instance, we write

<input
  type="number"
  oninput="this.value = (parseInt(this.value) || 0)"
  placeholder="0-9"
  autofocus=""
  value="0"
/>

to add a number input with the oninput attribute set to this.value = (parseInt(this.value) || 0).

The code is run as we type.

And it calls parseInt to parse the input value into an integer.

We then assign that as the new input value.

Leave a Reply

Your email address will not be published. Required fields are marked *