最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin9PV0评论

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

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far