jQuery keypress() Method triggers the keypress event when any button on the keyboard is pressed down. This method doesn’t consider keys such as ALT, CTRL, SHIFT, ESC. This method attaches an html element to event handler function, this event handler function executes when the keypress event occurs.
jQuery keypress() Method Syntax
$("input").keypress(function(){ //this code executes when the keypress event occurs. });
Here we have selected input text field $(“input”) using jQuery selector and the keypress() method attaches this html element to the keypress event handler function, which means the keypress event will only trigger when a key is pressed inside the text box field.
jQuery keypress() Example
In the following example, we are using keypress event to count the number of characters in the input text field. To do this we have attached the input text field to the event handler function using keypress() method. This triggers the keypress event each time a key is pressed inside the text field, in the event handler function we are increasing the counter each time a key is pressed and displaying the same in the “span” area.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> count = 0; $(document).ready(function(){ $("input").keypress(function(){ $("span").text(count = count+1); }); }); </script> </head> <body> <h2>jQuery keypress event example on Beginnersbook.com</h2> Write anything here: <input type = "text"> <p>The current characters count in the textbox is: <span>0</span></p> </body> </html>
Output:
Before any key is pressed:
This screenshot is taken after the page is loaded in the browser and we have performed no activity on the page.
After we have typed a word in the text field:
This screenshot is taken after we have typed a word “BeginnersBook” in the input text field. As you can see in the following screenshot, we are able to see the characters count in the span area below the input text field. The count increases simultaneously as we type the word in the text field.
Leave a Reply