How to Make Inputs Only Accpet Integer Numbers

How to make inputs accept only integers. One way is to set the increment to 1 and type to number like this one:

<input type = "number" step = "1">
But this has some flaws although users can only change the input number by 1 each time they hit the up or donw arrow on the right of the input, they can actually manually type in some number that is not an integer such as 1.5.

Solution

Now with a little JavaScript code, we can make an input strictly accept integers
<input oninput = "this.value = parseInt(this.value)" type = "number">
<input oninput = "this.value = Math.floor(this.value)" type = "number">
<input oninput = "this.value = Math.ceil(this.value)" type = "number">
Now, users can't type in non integer values

Accepting Only Positive Integers.

What about accepting only positive integers? Try the following.
<input oninput="this.value = this.value <= 0 ? -parseInt(this.value) : parseInt(this.value); " type = "number"/>

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser