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.

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

<input onkeypress="javascript:keyPressed(event);" type="text" />
This entry was posted in IT, Programming and tagged . Bookmark the permalink.

One Response to Using Javascript to detect the key pressed

  1. Dan says:

    Thanks. I was after a simple pointer how to detect which key was pressed. This is perfect.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

2,103 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>