我正在尝试将用户输入限制为 ascii 字符。它适用于普通键盘,但当我按下数字键盘上的键时不起作用。我试过了event.keycode
,event.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();
}
}
});