Home > Web Front-end > JS Tutorial > How Can I Determine the Pressed Key in a jQuery Keypress Event?

How Can I Determine the Pressed Key in a jQuery Keypress Event?

Patricia Arquette
Release: 2024-12-09 11:07:07
Original
468 people have browsed it

How Can I Determine the Pressed Key in a jQuery Keypress Event?

Determining the Pressed Key in jQuery Keypress Event

When binding to the keypress event in jQuery, there are two properties that can be used to identify the pressed key: keyCode and which.

Using keyCode and which

You can find out which key was pressed using the keyCode or which property of the event object.

$('#searchbox input').bind('keypress', function(e) {
  var code = e.keyCode || e.which;
  if (code == 13) { //Enter keycode
    //Do something
  }
});
Copy after login

Variation in Browser Support

Some browsers provide both keyCode and which, while others may only provide one. Generally, which is preferred in newer browsers, while keyCode is supported in older browsers.

Submitting on ENTER Key

To trigger a submit when the ENTER key is pressed, you can use the following code:

$('#searchbox input').bind('keypress', function(e) {
  var code = e.keyCode || e.which;
  if (code == 13) {
    $(this).closest('form').submit();
  }
});
Copy after login

The above is the detailed content of How Can I Determine the Pressed Key in a jQuery Keypress Event?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template