How can I detect pressing Enter on the keyboard using jQuery?

Learn, how to detect pressing of Enter key on keyboard using jQuery?
Submitted by Pratishtha Saxena, on August 30, 2022

prerequisite: Adding jQuery to Your Web Pages

Sometimes, it is necessary to figure out how and know when which key is pressed by the user on the keyboard so that some other events are queued accordingly.

Therefore, jQuery provides a keypress() method for the same. This method helps to trigger an event or some function that is attached to it when any key is pressed. There are similar methods like keypress() - keyup(), keydown(), etc. whose functions can be easily assumed.



Hence when any key is pressed the function gets triggered. Now, to find whether the key pressed is the ENTER key, we need to specify the ASCII value of the enter key which is 13. To achieve this, this condition is specified within the function. If the key pressed is ENTER, i.e., the value of the key pressed is 13 then further implementation of the function will go on.

Let's get into an example of this.

Example to detect pressing Enter on the keyboard using jQuery

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src=""></script>
    <style type="text/css">
      border: 5px solid rgb(32, 125, 218);
      background-color: rgb(0, 0, 0);
      height: 100px;
      width: 200px;
      font-size: large;
      color: rgb(3, 30, 164);
      font-weight: bolder;
      font-style: italic;
      font-style: oblique;
    <h2>Detect Pressing ENTER Key on Keyboard Using jQuery.</h2>
    <p>Write 'APPLY CSS' in the following text box and hit ENTER to see the result.</p>
    <label>Write Here: </label>
    <input type="text" id="myText">
  <script type="text/javascript">
                if (event.which == 13){


Example 1: Detect pressing Enter on the keyboard using jQuery

Example 2: Detect pressing Enter on the keyboard using jQuery

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.