views:

1208

answers:

3

Hi
I am using this code snippet to add KeyDown event handler to any element in the html form

for(var i=0;i<ele.length;i++)
{
    ele[i].onkeydown = function()
    {
            alert('onkeydown');
    } 
}

How can I know which key has been pressed on keydown event? I try this

for(var i=0;i<ele.length;i++)
{
    ele[i].onkeydown = function(e)
    {
           alert(e.KeyCode);
    } 
}

but it is not working, why? Thanks a lot

A: 

It is keyCode, not KeyCode.

David Dorward
not the mater, e is undefined at all
ArsenMkrt
+1  A: 

This is the code I use for this problem. It works in every browser.

//handle "keypress" for all "real characters"     
if (event.type == "keydown") {
    //some browsers support evt.charCode, some only evt.keyCode
   if (event.charCode) {
      var charCode = event.charCode;
   }
   else {
      var charCode = event.keyCode;
   }
}
Bobby
Thanks, it works great, can I change this code to tab? event.charCode = 9 or event.keyCode = 9 is not working :(
ArsenMkrt
You can try it by printing the char code when pressing keys in different browsers to see the exact code to use. In my experience some keys have different codes in IE and Mozilla
Bobby
It works great, Thank you very much...
ArsenMkrt
Really? Is that working in non-IE browsers? Where does `event` come from?
Tim Down
I tested it only on IE, do you have suggestion for non IE browsers @Tim?
ArsenMkrt
Yes, see my answer.
Tim Down
+1  A: 

For detecting Enter, you could use the following code, which will work in all mainstream browsers. It uses the keypress event rather than keydown because Enter produces a printable character:

ele[i].onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    if (charCode == 13) {
        alert("Enter");
        // Do stuff here
    }
};
Tim Down
I will test it and give you know
ArsenMkrt