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

jquery - Trying to get numbers from keypress document, javascript - Stack Overflow

programmeradmin3浏览0评论

it seems simple, but I couldn't figure how to intercept numbers on javascript from Document DOM

    $(document).keypress(function (e) {
        if (e.keyCode == xx) {
            alert();
        }
    });

it seems simple, but I couldn't figure how to intercept numbers on javascript from Document DOM

    $(document).keypress(function (e) {
        if (e.keyCode == xx) {
            alert();
        }
    });
Share Improve this question asked Jun 3, 2012 at 4:55 RollRollRollRoll 8,47220 gold badges79 silver badges137 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 7

Numbers are 48 through 57, so...

$(document).keypress(function (e) {
    var key = e.keyCode || e.charCode;
    if (key >= 48 && key <= 57) {
        alert('You pressed ' + (key - 48));
    }
});

See demo

Source: http://www.quirksmode/js/keys.html

Keypress events yield a keyCode of 0 in Firefox, and the ASCII character value everywhere else. Keypress events yield a charCode of the ASCII character value in Firefox. Therefore, you should use (e.keyCode || e.charCode) to get the character value.

Also note that your code also wouldn't work because alert should accept one argument. In Firefox, at least, calling alert with no arguments throws an exception.

With those two issues fixed, your code will now be:

$(document).keypress(function (e) {
    if ((e.keyCode || e.charCode) == <number from 48..57 inclusive>) {
        alert('something');
    }
});

Example: http://jsfiddle/gRrk6/

$(document).keydown(function(event){ if(event.keyCode == 13) { alert('you pressed enter');} }); replace 13 with the keys code, see here for details: http://www.cambiaresearch./articles/15/javascript-char-codes-key-codes

you should notice the differences between events [ keyCode, charCode, which ] and this test page affected by the browser i.e i tested it on safari the onKeyPress always empty

JavaScript Event KeyCode Test Page

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论