最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - wrong ASCII key code for delete key - Stack Overflow

programmeradmin1浏览0评论

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 ing correct. I am not able to find were am I going wrong. Please help

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 ing correct. I am not able to find were am I going wrong. Please help

Share Improve this question edited Jun 27, 2014 at 10:15 Sr.Richie 5,7405 gold badges40 silver badges62 bronze badges asked Jun 27, 2014 at 8:45 shikhathakurshikhathakur 152 silver badges7 bronze badges 3
  • 2 check this : cambiaresearch./articles/15/javascript-char-codes-key-codes – Amit Commented Jun 27, 2014 at 8:52
  • javascriptkit./javatutors/javascriptkey2.shtml – Sasi Commented Jun 27, 2014 at 8:59
  • thanks @Sasi. The code helped me!!! – shikhathakur Commented Jun 27, 2014 at 9:15
Add a ment  | 

1 Answer 1

Reset to default 5

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
  });
});
发布评论

评论列表(0)

  1. 暂无评论