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

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

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
  });
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745088843a4610566.html

相关推荐

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

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

    11小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信