Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent html input type=number from ever being empty

Tags:

html

input

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.

like image 941
Josh L Avatar asked Jan 10 '17 20:01

Josh L


People also ask

How do you prevent input type numbers?

If you are able/allowed to use jQuery, you can disable keypress on the type='number' . $("[type='number']"). keypress(function (evt) { evt. preventDefault(); });

Is there any way to prevent input type number getting negative values?

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.


1 Answers

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" />
like image 91
Brett DeWoody Avatar answered Sep 19 '22 07:09

Brett DeWoody