JQuery :: How to do action on an element on key press?

In our previous article which was JQuery :: How to pass values to select box via ajax? we discussed how we can pass values to a select box via ajax using jquery. Today we will like to focus on how we can do an action on an element on  key press.

Like any other programming language Jquery and Ajax is also event based. As long as the user does not do anything the event is not triggered and it does nothing. Some events are implicit events i.e. which user does not directly do like opening a page, in which scenario it is not done by user but is actually done by user. I know i am contradicting myself, but there is a reason behind it. The reason is when users open a document they do not implicitly do any action on your webpage but simply open it but they do trigger an event. That is why it is called implicit events.

Than there are events which are explicitly done by users like keypress or click or scroll and so on. These are done by users on an element on your webpage and there are triggered only when user’s do them.

Our focus today is how can we do an action on an element when users press key.

In your HTML document add an HTML element which id “testingEvent” as follows:

<input type=”text” id=”testingEvent” name=”testingEvent” />

This will declare a HTML element which id testingEvent on your webpage.

Our goal is to catch the event which is triggered when users press a key inside the testingEvent element. In order to do the same, we will add in the following javascript code:

$(“#testingEvent”).die(‘keypress’);
$(“#testingEvent”).live(‘keypress’, function(e)
{
}

In the above code we have use .die function of JQuery because we want to disable the original event that happens when users press a key in the text box, e.g. when enter is pressed in a text box the form is submitted and if you do not want to submit the form you use the die function to accomplish that.

In the above code you can add in whatever code you wish to execute once the key is pressed. If you want to execute code once enter is pressed use the following code:

$(“#testingEvent”).die(‘keypress’);
$(“#testingEvent”).live(‘keypress’, function(e)
{

if(e.which == 13)

{

// add code here…

}
}

In the above code the e.which == 13 lets us know when enter is pressed since the ASCII code for enter is 13.

We will keep updating our Jquery Tips section every 4 days, please subscribe to our feed and also share our articles on Facebook and Google Plus so other’s can benefit from our insight. Please feel free to send us your comments below, on how we can improve.