Describe the keypress event in jQuery.

The jQuery keypress event is triggered after a key is pressed in the keyboard. The keypress method will be used to perform any action or run a function as the keypress event occurs in your web document. The keypress event occurs when a key is pressed down, so it is quite similar to the keydown event. However, there are differences between the two – for example pressing a few keys will trigger only the keydown event like ALT, CTRL, ESC etc.
Also, the keypress event returns different values for lowercase and uppercase letters, whereas the keyup and keydown return the same. So it is useful to use keypress event in case you have to differentiate between lowercase and uppercase keys.
The keypress method can be useful for many scenarios, for example, in passwords boxes only allowing letters, numbers and a few special characters while notifying users if a specific key is not allowed. In that case, rather than sending a request to the server and then checking the input by the visitor, you can check it at the client side by using the jQuery keypress.

Syntax of jQuery keypress method

$(selector).keypress(function)
Where the function is optional to execute as the keypress event occurs.
An example of keypress event
The example below shows as a key (in your keyboard) is pressed, and keypress event occurs. The keypress method will capture the event and throw an alert with ASCII value of the pressed key.

<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
  $("#keyboard").keypress(function(){ 
    alert("keypress event occured! The ASCII value of pressed key is: " + event.keyCode); 
  }); 
}); 
</script> 
</head> 
<body> 
Enter keyboard keys: <input type="text" id="keyboard"> 
</body> 
</html>

Need Help? Contact Us.

Log in

*
*

Forgot password?

*

New User

*
*
*
*