Do the numbers on a numeric keypad have a different keycode than the numbers at the top of a keyboard?

以下是一些应该在keyup事件上运行的JavaScript,但仅当键码在48到57之间时才会运行.以下是代码:

$('#rollNum').keyup(function(e) {
    if(e.keyCode >= 48 && e.keyCode <= 57) { //0-9 only
        var max = 15;
        var textLen = $(this).val().length;
        var textLeft = max - textLen;
        . . . 

My problem is that this code only runs in response to the numbers entered at the top of the keyboard, but does not run in response to numbers entered from the numeric keypad.

I'm thinking the answer must be that the numeric keypad has different keyCode values, but how do I find out what those are?

推荐答案

The keycodes are different. Keypad 0-9 is Keycode 96 to 105

Your if statement should be:

if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) { 
  // 0-9 only
}

Here's a reference guide for keycodes


-- UPDATE --

This is an old answer and keyCode has been deprecated. There are now alternative methods to achieve this, such as using key:

if ((e.key >= 48 && e.key <= 57) || (e.key >= 96 && e.key <= 105)) { 
  // 0-9 only
}

Here's an output tester for event.key, thanks to @Danziger for the link.

Jquery相关问答推荐

如何根据另一个 radio Select 并切换?

5 秒后关闭 jQuery 弹出模式

在 `click` 和 `enter` 上触发事件

jQuery JSON到字符串?

如何使用给定的 url 判断图像是否存在?

jQuery 中 prop() 和 attr() 的区别以及何时使用 attr() 和 prop()

Backbone.js 和 jQuery

试图检测浏览器关闭事件

iframe 仅显示页面的特定部分

jQuery $.cookie 不是一个函数

如何使用 jQuery 进行带命名空间的 XML 解析

Select 除第一个之外的所有子元素

使用 jQuery DataTables 时禁用第一列的自动排序

jquery在加载时获取iframe内容的高度

使用 jquery 通过文本设置下拉值

jquery: $(window).scrollTop() 但没有 $(window).scrollBottom()

JQuery - 如何根据值 Select 下拉项

javascript过滤对象数组

在未实现接口 FormData 的对象上调用附加

AJAX 成功中的 $(this) 不起作用