Tutorialspoint.dev

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.

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

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.

<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>

/div>

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.

<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>

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.



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter