Ralph J. Smit Laravel Software Engineer
I recently found myself in the situation where I was using an HTML
Let's start with a simple HTML input element. This element is just an input element and nothing more. As you see, you can still
type negative and positive numbers;
use the arrows to get both positive and negative numbers
The HTML input `min` attribute
Well, it turns out that the
<input> element can have a special attribute: the
min attribute. Problem solved, isn't it? Well, it turns out that we here only have one part of the solution.
Try out the Codepen:
<input type="number" min="0">
As you see, it's now not possible anymore to add negative numbers with the arrows. But you still can type both negative and positive numbers. How to fix this?
To disallow the typing of negative numbers, we need to add the
<input type="number" min="0" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))">
As you've seen, to only allow positive integers (whole numbers), you can combine the use of the
min attribute and the
Have you used this yourself or have you got a better hack? Let me know in the comments! ✌️👇
Published by Ralph J. Smit on in Guides. Last updated on 10 March 2022.
Like what you read?
Get notified when I publish something new, and unsubscribe at any time.