jQuery | keypress()

The keypress() method in jQuery 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 code to show the working of keypress() Method:

Code #1:
Below code is used to check if a key is pressed anywhere on the page or not.

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
<head>
<title>Jquery | Keypress() </title>
</script>
</head>
<script>
$(document).keypress(function(event){
      
        alert('You pressed a key');    
});
</script>
<body>
</script>
</body>
</html>

chevron_right


Output:

Code #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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

If any key is pressed then output will be-

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
<head>
<title>Jquery | Keypress() </title>
</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>

chevron_right


Output:

When enter key is pressed inside the above textbox then output becomes like below-

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

self motivated and passionate programmer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.