I'd like to block users from typing certain characters in a text box (want to only allow [a-z], [A-Z], and underscore). I took this from a previous Q, but if I press the arrow keys (in FF 3.6), I get a js error:
"window.event is undefined"
this is the original code, what can I change window.event to in this case?:
$("#myTextBox").bind("keypress", function(event) {
var charCode = (event.which) ? event.which : window.event.keyCode;
if (charCode <= 13) {
return true;
}
else {
var keyChar = String.fromCharCode(charCode);
var re = /[a-zA-Z_]/
return re.test(keyChar);
}
});
Thanks
You can do just this:
$("#myTextBox").bind("keypress", function(event) {
var charCode = event.which;
if (charCode <= 13) return true;
var keyChar = String.fromCharCode(charCode);
return /[a-zA-Z_]/.test(keyChar);
});
jQuery normalizes event.which
already...and you can test it here :)
If it didn't, the fix would just be event.keyCode
, you want to refer to the event
passed as the parameter to this function, not a property on window
. In this case, if the if
condition was true, it'd return...so there's no need for an if
/else
, you can simplify it like I have above.
I'm not sure if it'll be right for you, but perhaps you might want to use the Masked Input Plugin?
Just remove the window because your event is defined in jQuery ($)
精彩评论