Reputation: 1550
I am developing an HTML page with many textfields like userid and username, I have added a javascript code like this in separate .js file
function CommonKeyPressIsAlpha(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123)){
document.getElementById("errordisp").innerHTML = "";
return true;
}else{
document.getElementById("errordisp").innerHTML = "Please enter a valid name!";
return false;
}
}
Whenever user types in username text field, I am calling this function to validate that user types only characters. I am calling this function in username text fields:
onkeypress="return CommonKeyPressIsAlpha(evt);"
It works fine in chrome but not in firefox and in IE, Whats the problem?
Upvotes: 1
Views: 2145
Reputation: 35084
Your code is relying on a Chrome bug where the anonymous function compiled for an inline event handler (onkeypress
in your case) has its one argument named evt
in Chrome. The spec calls for that argument to be named event
. See http://code.google.com/p/chromium/issues/detail?id=80912
The solution is to use onkeypress="return CommonKeyPressIsAlpha(event);"
Upvotes: 2
Reputation: 324737
You need to pass event
into the handler in your onkeypress
attribute:
onkeypress="return CommonKeyPressIsAlpha(event);"
This works in all major browsers but relies on using event
rather than evt
in the attribute. I've written about the details of how this works on SO before.
Upvotes: 3