Thursday, September 20, 2018

Capturing a Key-Press/Key-Down Event for the Enter Key in jQuery

You may want to capture an enter key action whenever the user hits the enter key. This can be used to submit a form without having to use the mouse, or it can provide some other feature.

To do this, we bind the keydown() event to the document, and check the event to make sure it is 13 (the enter key). A different integer represents a different key (27 is the escape key, etc.).

We do the binding like this...

$(document).keydown(function(event) {
if (event.which === 13) {
// do something now that the enter key is hit
}
});

You can also use the keypress() event. But there is a problem with keypress -- this event does not fire for the escape key, or the up-down arrows. It only fires for keys whose purpose is to create a character.

No comments:

Post a Comment