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

it seems simple, but I couldn't figure how to intercept numbers on javascriptfrom Document DOM$(

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

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

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

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

关注微信