Backspace and non-Firefox space

I have the following check to allow only numbers and decimal numbers 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 to do the same with Firefox's backspace, the left and right arrow keys and spacebar don't work.

How can i fix this?

+4
source share
4 answers

Using a keystroke is the right solution, but you just need to attach a JS event handler (which is considered best 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
source
0

keydown function will work in all browsers. Please use the keydown function and it will work!

Example: -.

$(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
                    }
                    });
0
source

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 code 0.

0
source

All Articles