Backspace and space not working in Firefox

6.8k views Asked by At

I have the following validation to allow only numbers and a decimal in Javascript

function validate(evt) {
      var theEvent = evt || window.event;
      var key = theEvent.keyCode || theEvent.which;           
      key = String.fromCharCode( key );
      var regex = /[0-9]|\./;
      if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
      }
}

I call this in my textbox element like onkeypress='validate(event)'

This code works fine in IE but when I try the same with Firefox backspace, left and right arrow keys and space does not work.

How would I fix this?

4

There are 4 answers

0
LiorST On

Using key press is the right solution, but you simply need to attach the event handler by JS (which is considered better practice anyway), and use something like this:

$('#myInput').keypress(function(event){
   validate(event)
});

function validate(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;           
  if (key <48 || key > 57  || key == 190)//keycode is a number between 0 and 9 or '.'
       ...
};
1
exussum On

use keyup or keydown instead of keypress

keypress is only supposed to fire when there is a character insert

http://www.quirksmode.org/dom/events/keys.html

0
user3383498 On

Try

    //allows number and hyphen only 
    function isNumeric(e)
    {
        var a = e.charCode;
        if(a==0){return;}
        return ((a >= 48 && a <= 57));
    }
    </script>

Firefox Backspace charcode 0.

1
abhinsit On

keydown function would work across all browsers. Please use keydown function and it would work!

Ex.:-

$(document).keydown(function (e){
                    if(e.keyCode == 37) // left arrow
                    {

                    //code for left arrow

                    }
                    else if(e.keyCode == 39)    // right arrow
                    {

                   //code for right arrow
                    }
                    });