Robert Pitrone
Robert Pitrone

Reputation: 119

Backspace not working in Firefox in input field

I have this input filed with an onkeypress event:

<input type="number" min = "0" id = "count" onkeypress='return event.charCode >= 48 && event.charCode <= 57' /> 

Basically this allows only numeric values to be entered into the field...and this works just fine... in Chrome, Firefox and IE.. which is enough for me. BUT the "backspace" key does not work in Firefox. It works fine in Chrome and IE. What I mean is if I want to type '15' and by accident I type '155'... when in Firefox I am not able to use "backspace" on that field. How can I make backspace work in Firefox?

Upvotes: 1

Views: 8367

Answers (4)

wild coder
wild coder

Reputation: 900

Below jQuery code snippets will allow only numbers in the textbox. However backspace and delete keys are also allowed.

   $("#testID").keydown(function(e) {
    if (e.shiftKey)
     e.preventDefault();
    else {
     var nKeyCode = e.keyCode;
     //Ignore Backspace and Tab keys
     if (nKeyCode == 8 || nKeyCode == 9)

      return;

     if (nKeyCode < 95) {
      if (nKeyCode < 48 || nKeyCode > 57)
       e.preventDefault();
     } else {
      if (nKeyCode < 96 || nKeyCode > 105)
       e.preventDefault();
     }
    }
   });

Upvotes: 1

First Last
First Last

Reputation: 45

Try this method for only allowing numbers instead:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
<input type="number" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />

https://jsfiddle.net/6dfrLz0p/12/

Upvotes: 0

xuv
xuv

Reputation: 124

You can add a catch for the Backspace key:

<input type="number" min = "0" id = "count" onkeypress='return event.charCode >= 48 && event.charCode <= 57 || event.key === "Backspace"' /> 

Upvotes: 0

Sachin Singh
Sachin Singh

Reputation: 948

You might want to do this:

var input = document.querySelector('#count');
input.addEventListener('input', function (e) {
  return (e.keyCode === 8 || (e.keyCode >=48 && e.keyCode <=57));
});
<input type="number" min="0" id="count">

Upvotes: 0

Related Questions