While creating HTML5 input type number in the html form, I would like to disable or prevent user from entering negative number in it, user should be able to enter only positive number, how can i do that, current HTML code is as below
<input type="number" id="Price" name= "Price" />
The simplest solution is to use HTML like below
<input type="number" min="0" id="Price" name= "Price">
The above code will help you but not completely, so you would have add Javascript, to prevent user from being entering a negative value using the keyboard
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;
}
}
Here is the full fiddle example.
OR
Simply use below HTML, with in-line Javascript, which will allow 0 or greater tha 0 value.
<input type="number" min="0" oninput="this.value =
!!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">
If you want to enter float in the input type and prevent negative value, you can use below code
<input type="number" min="0.01" step="0.01">
OR
You can also use onKeyup event, which will convert negative number into positive.
<input type="number" onkeyup="if(this.value<0){this.value= this.value * -1}">
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly