Javascript – wrong ASCII key code for delete key

asciijavascriptkeycode

I have an HTML form in which I need to allow only numeric key-press. For this i have used the following code

    $(".span8").keypress(function(e) 
    {
         var unicode=e.charCode? e.charCode : e.keyCode
     //alert(unicode);
     if ((unicode ==8) || (unicode==9)|| (unicode==46)){
        //if the key isn't the backspace key (which we should allow)
     }
     else
     {
         if (unicode<48||unicode>57&&unicode!=65) //if not a number
         return false //disable key press
     }

});

but here if I am testing keycode, I am getting value as 46 for delete key. 46 is for dot(- period)
Others values are coming correct. I am not able to find were am I going wrong.
Please help

Best Answer

I've found this weird behaviour too with the keypress function.

Instead, try the following:

jQuery(function($) {
  var input = $('.span8');
  input.on('keydown', function() {
    var key = event.keyCode || event.charCode;

    if(key == 8 || key == 46)
        //Do something when DEL or Backspace is pressed
  });
});