Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50712

element onkeydown keycode javascript

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

Upvotes: 3

Views: 31473

Answers (4)

Samuel-Anton
Samuel-Anton

Reputation: 31

I used this:

function check(){
 if (event.keyCode == 32){
  alert("Space is pressed");
 }
}

and in my body tag: onKeyPress="check()"

Upvotes: 3

Tim Down
Tim Down

Reputation: 324567

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
    }
};

Upvotes: 3

Bobby
Bobby

Reputation: 1611

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;
   }
}

Upvotes: 6

Quentin
Quentin

Reputation: 943510

It is keyCode, not KeyCode.

Upvotes: 0

Related Questions