How to detect pressing Enter on keyboard using jQuery?

To detect pressing Enter on keyboard, use the keyup() function with keyCode. The Enter key has a keyCode of 13, which can be checked when the keyup event is triggered. You can try to run the following code to learn how to detect pressing Enter on keyboard using jQuery −

Example

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
            $('textarea').bind("enterKey",function(e){
               alert("You have pressed Enter key!");
            });
            $('textarea').keyup(function(e){
               if(e.keyCode == 13) {
                  $(this).trigger("enterKey");
               }
            });
         });
      </script>
   </head>
   <body>
      <p>Press Enter below</p>
      <textarea rows="2" cols="20"></textarea>
   </body>
</html>

In this example, we bind a custom event called enterKey to the textarea element. When the keyup event occurs, we check if the keyCode is 13 (Enter key) and then trigger our custom enterKey event, which displays an alert message.

Alternative Method Using Direct Event Handling

You can also detect the Enter key directly without using custom events −

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
            $('input').keyup(function(e){
               if(e.keyCode == 13) {
                  alert("Enter key pressed in input field!");
               }
            });
         });
      </script>
   </head>
   <body>
      <p>Type something and press Enter</p>
      <input type="text" placeholder="Type here and press Enter">
   </body>
</html>

This method directly checks for the Enter key press in the keyup event handler without creating a custom event. Both approaches are effective for detecting Enter key presses in jQuery applications.

Updated on: 2026-03-13T20:51:17+05:30

399 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements