I know HTML 5 allows for input of type number
where it only allows the user to enter inputs of type digits. When my page loads I set my default input to 0 but the user can just erase this value so that when the user hits submit a blank input (null) is submitted? Is there a way so that when the user erases all numbers in the input the value defaults back to 0? I'm not talking about validation here.
Trying to avoid an ugly JS hack but if that's the only way then I guess I'll have to go that route.
If you are able/allowed to use jQuery, you can disable keypress on the type='number' . $("[type='number']"). keypress(function (evt) { evt. preventDefault(); });
As we know, the <input type="number"> specifies a field for entering a number. If you want to restrict the <input> field to only positive numbers, you can use the min attribute.
HTML5 validation rules will only help when the form is submitted. If you want to prevent the input from being empty you'll need to use some JS.
The following (not "ugly JS hack") will work for all number
inputs on a page and insert a value of 0
if the user tries to leave the input empty.
const numInputs = document.querySelectorAll('input[type=number]')
numInputs.forEach(function(input) {
input.addEventListener('change', function(e) {
if (e.target.value == '') {
e.target.value = 0
}
})
})
<input type="number" required value="0" />
<input type="number" required value="0" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With