I am trying to restrict the user input to ascii characters. It works on regular keypad, but doesn't work when I press keys on numeric keypad. I tried event.keycode
and event.which
both result the same. How do I get the correct code? Here is the link: http://jsfiddle.net/rg85Y/1/
Here is the 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>
Here is the 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();
}
}
});