Is there any way to prevent input type="number" getting negative values?
For me the solution was:
<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
Edit
As suggested on the comments with a minor change to work if 0 is the min value.
<input type="number" min="0" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
Use the min
attribute like this:
<input type="number" min="0">
This code is working fine for me. Can you please check:
<input type="number" name="test" min="0" oninput="validity.valid||(value='');">
I was not satisfied with @Abhrabm answer because:
It was only preventing negative numbers from being entered from up/down arrows, whereas user can type negative number from keyboard.
Solution is to prevent with key code:
// Select your input element.
var number = document.getElementById('number');
// Listen for input event on numInput.
number.onkeydown = function(e) {
if(!((e.keyCode > 95 && e.keyCode < 106)
|| (e.keyCode > 47 && e.keyCode < 58)
|| e.keyCode == 8)) {
return false;
}
}
<form action="" method="post">
<input type="number" id="number" min="0" />
<input type="submit" value="Click me!"/>
</form>
Clarification provided by @Hugh Guiney:
What key codes are being checked:
- 95, < 106 corresponds to Numpad 0 through 9;
- 47, < 58 corresponds to 0 through 9 on the Number Row; and 8 is Backspace.
So this script is preventing invalid key from being entered in input.