Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

Using Javascript to Detect the Key Pressed

Often it is useful to intercept the key pressed within an element of an HTML form, like a textbox and so on. For this purpose you can use Javascript to extract the code of the key that was pressed. Here is a snippet of code you can use–of course adapting it to your needs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function keyPressed(e){
  var code;
  if(window.event){ //IE
   code = e.keyCode;
  }
  else{ //other browsers
    code = e.which;
  }
  //check, for example, if the Enter key was pressed (code 13)
  if(code == 13){
    //Enter key pressed
  }
  else{
    //Another key pressed
  }
}

Note: keyCode is used by Internet Explorer while which is used by the other browsers.

Then, from within a form, you can call this function. For example

1
<input onkeypress="javascript:keyPressed(event);" type="text" />

Comments