我试图将用户输入限制为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();
}
}
});