Skip to content
Related Articles

Related Articles

jQuery keypress() Method

Improve Article
Save Article
  • Last Updated : 18 Nov, 2022
Improve Article
Save Article

The jQuery keypress() method triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not. 

Syntax: To trigger the keypress event for the selected elements:

$(selector).keypress()

To attach a function to the keypress event:

$(selector).keypress(function) 

jQuery examples to show the working of keypress() Method:
Example 1: Below code is used to check if a key is pressed anywhere on the page or not. 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Jquery | Keypress() </title>
    <script src=
    </script>
  
    <script>
        $(document).keypress(function (event) {
  
            alert('You pressed a key');
        });
    </script>
</head>
  
<body>
    <h1>Try pressing any printable character from the keyboard</h1>
</body>
  
</html>

Output: 

 

 

Example 2: To detect any specific key event.keyCode and event.which will return an ASCII value of the pressed key, Both are browser specific.Below code is used to check which key is pressed on the page. 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Jquery | Keypress() </title>
    <script src=
    </script>
  
    <script>
        $(document).keypress(function (event) {
  
            var key = (event.keyCode ? event.keyCode : event.which);
            var ch = String.fromCharCode(key)
            alert('You pressed key : ' + ch);
        });
    </script>
</head>
  
<body>
    <br><br>
    <center>
        <h1>Try pressing any printable character from the keyboard </h1>
    </center>
</body>
  
</html>

Output:  

 

Example 3: Below code is used to check if Enter key is pressed inside a textbox on the page or not. 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Jquery | Keypress() </title>
    <script src=
    </script>
</head>
  
<body>
    <center>
        <br><br>
        <h1>Press " Enter key " inside the textbox </h1>
        <input id="textbox" type="text" size="50" />
    </center>
      
    <script type="text/javascript">
        $('#textbox').keypress(function (event) {
  
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if (keycode == '13') {
                alert('You pressed "enter" key in textbox');
            }
            event.stopPropagation();
        });
    </script>
</body>
  
</html>

Output:  

 

Note: The keypress event is not triggered for all keys like non printing characters (e.g. ALT, CTRL, SHIFT, ESC). keydown() method can be used to check these keys.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!