How to Check if an Enter Key is Pressed with jQuery

If you want to check whether the user clicks the press button on keyboard, you can use the keypress() method.

The key code of Enter key is 13, which is supported in all major browsers. Attach the keypress() method to document for checking whether the key is pressed on page:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://code.jquery.com/jquery-3.5.0.min.js">
    </script>
  </head>
  <body>
    <h1>Check if an Enter Key is Pressed with jQuery</h1>
    <label>TextBox : </label>
    <input id="textbox" type="text" size="40" />
    <script>
      $(document).on('keypress', function(event) {
          let keycode = (event.keyCode ? event.keyCode : event.which);
          if(keycode == '13') {
            alert('You pressed a "enter" key in somewhere');
          }
        });
    </script>
  </body>
</html>
You can also use e.keyCode instead of e.which, however e.which is much recommended.

The keypress() Event

The keypress binds an event handler to the "keypress" JavaScript event or triggers that event on an element. The keypress event is sent to the element when the browser registers keyboard input. The keypress event handler can be bound to any element, but the event is only sent to the element which has the focus.

The event.which Property

The event.which property indicates the specific key/button which was pressed for key or mouse events. It normalizes event.keyCode and event.charCode. It is much recommended to use event.which for keyboard key input as it provides cross browser compatibility.