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 =
</ 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 =
</ 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 =
</ 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: Â
Last Updated :
20 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...