Input [number] accept only numbers in Firefox

4

How do I make the input [number] field accept only numbers in Firefox? In Chrome, Opera and Edge works perfectly, but in Firefox the [number] field accepts letters and spaces.

<inputtype="number" name="EstoqueProd[]" class="form-control" min="1" value="1"/>
    
asked by anonymous 01.11.2017 / 15:27

1 answer

4

You can force this with a keydown event handler that detects if the entered character is a digit by comparing the key code.

An example would be:

var input = document.querySelector('input[name="EstoqueProd[]"]');
input.addEventListener('keydown', function(e) {
  var numero = (e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105);
  var controlos = [8, 37, 39].includes(e.keyCode);
  if (!numero && !controlos) return e.preventDefault();
});
<input type="number" name="EstoqueProd[]" class="form-control" min="1" value="1" />

jsFiddle: link

    
01.11.2017 / 15:31