Open In App

How to check whether the enter key is pressed in a textbox or not using JavaScript / jQuery ?

Given a textarea element and the task is to check the user presses enter key with the help of JQuery.

Example 1: In this example, the keyup event is added to the textarea, when it occurs then a new event enterKey is triggered by keyup event.




<!DOCTYPE HTML> 
<html
    <head
        <title
            Event for user pressing enter
            button in a textbox
        </title>
          
        <script src
        </script>
    </head
  
    <body style = "text-align:center;">
           
        <h1 id = "h" style = "color:green;"
            GeeksForGeeks 
        </h1>
          
        <p id = "GFG_UP" style
            "font-size: 15px; font-weight: bold;">
            click the Enter Key inside the textarea.
        </p>
          
        <textarea></textarea>
        <br>     
          
        <p id = "GFG_DOWN" style
            "color:green; font-size: 20px; font-weight: bold;">
        </p>
          
        <script>
            $('textarea').keyup(function(e) {
                if(e.keyCode == 13) {
                    $(this).trigger("enterKey");
                }
            });         
            $('textarea').on("enterKey", function(e){
                $("#GFG_DOWN").text("Enter key pressed inside textarea");
            });                             
        </script
    </body
</html>                    

Output:

Example 2: In this example, the keyup event is added to the textarea, when it occurs then a message-Enter key pressed inside textarea is printed on the screen without triggering a new event to handle it.




<!DOCTYPE HTML> 
<html
    <head
        <title
            Check enter key pressed in a
            textbox using JavaScript
        </title>
          
        <script src
        </script>
    </head
  
    <body style = "text-align:center;">
           
        <h1 id = "h" style = "color:green;"
            GeeksForGeeks 
        </h1>
          
        <p id = "GFG_UP" style =
            "font-size: 15px; font-weight: bold;">
            click the Enter Key inside the textarea.
        </p>
          
        <textarea></textarea>
        <br>     
          
        <p id = "GFG_DOWN" style
            "color:green; font-size: 20px; font-weight: bold;">
        </p>
          
        <script>
            $('textarea').keyup(function(e) {
                if(e.keyCode == 13) {
                    $("#GFG_DOWN").text("Enter key pressed inside textarea");
                }
            });                     
        </script
    </body
</html>                    

Output:


Article Tags :