[JavaScript] Checking Which Key is Pressed

You might want to hook up the handler function to multiple elements. How can you get the reference of the element that triggered the event?

1. window.event.keyCode

The “keyCode” property is to used to get the code of the key that is pressed as an integer value. It is IE only.

document.getElementById("txtBox1").onkeypress = onTextChange;

function onTextChange(e) {
  alert(window.event.keyCode);
}

 

2. which

The event object’s “which” property is the preferred way to get the key code.

document.getElementById("txtBox1").onkeypress = onTextChange;

function onTextChange(e) {
  alert(e.which);
}

 

3. jQuery

jQuery provides the normalized “which” property.

$(document).ready(function () {
  $("#txtBox1").keypress(onTextChange);
});

function onTextChange(e) {
  alert(e.which);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s