<input onkeydown="return testKey(event)" type="text"/>
function testKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
alert(charCode)
}
- This code works perfectly in IE with no errors
- In Firefox (Using FireBug to check for JS errors) the code alerts every character fine except for 1 key which is the ESC key. When i press the ESC key in that input field FireBug throws an error saying: "event is not defined". So for some retarded reason Firefox is looking at the event.keyCode part (which is supposed to be used for IE only) for only the ESC key (all other keys dont throw up an error).
EDIT: Ok i have figured out why its happening now, because Firefox charCode returns 0 and IE returns undefined and when you do 0 || undefined it returns undefined which i didnt think would be the case. Anyone have an idea how to get around the ESC key besides detecting for 0 and undefined?
Hi Fang,
Thank you for that, however if i needed to allow say for example only letters to be input in a field (including things like backspace, left arrow, right arrow, space) am i right in saying that this is the best way to do it?
var evt = window.event? window.event : e;
var keyCode = window.event? evt.keyCode : (evt.charCode || evt.which);
alert(keyCode)
if(keyCode==0)
{
//check charCode value to see if the key pressed was a left, right arrow or backspace. If it was any of those 3 then also return true
}
EDIT: The problem im having is that if i detect certain keys to allow them (like letters only in the above example) then i need to also account for left and right arrow keys which have a keycode value of 0...
I did that before however i ran into a problem, using your code if you allow the 37 keycode (for left arrow) then you are also allowing the "%" character aswell because it has a charCode of 37 and keycode of 0.
Ah right your using onkeydown whereas im using onkeypress that explains it, is it preferable to use the onkeydown instead? (Im just getting mixed up as to which one should be used where).
Thanks Kor, i was actually using this website alot to test for certain keys but when i read the special keys section i didnt realise other keys like arrow keys would also cause problems too.
Cheers for pointing that out aswell, appreciated
Bookmarks