Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

jQuery | keypress()

  • Last Updated : 13 Feb, 2019

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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!