jquery从keyInput获取正确的ascii字符

时间:2012-07-31 19:21:25

标签: jquery keydown numpad

我试图将用户输入限制为ascii字符。它适用于常规键盘,但在按数字键盘上键时不起作用。我尝试event.keycodeevent.which的结果都相同。我如何获得正确的代码?这是链接:http://jsfiddle.net/rg85Y/1/

这是html:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
</head>
<body>
    <input id="validateMe" type="text" />
</body>​

这是javascript:

$("#validateMe").keydown(function(event) {
        // Allow: backspace, delete, tab, escape, and enter
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || 
             // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) || 
             // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        else {
            // Allow only permitted chars
            var chr = String.fromCharCode( event.keyCode );
            alert(chr);
            if( !(/^[a-zA-Z\s'-]*$/.test(chr)) ) {
                event.preventDefault();
            }
        }
});​

0 个答案:

没有答案