Last Updated : 11 Jul, 2025
jQuery keypress() method triggers the keypress event whenever the browser registers a keyboard input. So, Using the keypress() method it can be detected if any key is pressed or not.
NOTE: The keypress event will not trigger for all keys like non-printing characters (e.g. ALT, CTRL, SHIFT, ESC). The keydown() method can be used to check these keys.
Syntax:$(selector).keypress(function)
Example 1: The below code is used to check if a key is pressed anywhere on the page or not using the keypress() method of jQuery.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Jquery | Keypress() </title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
$(document).ready(()=>{
$(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: The below code example will show you the name of the key pressed by you in the alert message using keypress() method.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Jquery | Keypress() </title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
$(document).ready(()=>{
$(document).
keypress(function (event) {
let key = (event.keyCode ?
event.keyCode :
event.which);
let character = String.
fromCharCode(key)
alert('You pressed key : '
+ character);
});
});
</script>
</head>
<body>
<h1>
Try pressing any printable
character from the keyboard
</h1>
</body>
</html>
Output:
Example 3: The below example will show an alert message if you click the enter key inside the input box.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Jquery | Keypress() </title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
$(document).ready(()=>{
$('#textbox').
keypress(function (event) {
let keycode =
(event.keyCode ?
event.keyCode :
event.which);
if (keycode == '13') {
alert('You pressed "enter" key in textbox');
}
event.stopPropagation();
});
});
</script>
</head>
<body>
<center>
<br><br>
<h1>
Press " Enter key "
inside the textbox
</h1>
<input id="textbox"
type="text"
size="50" />
</center>
</body>
</html>
Output:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4