jQuery keypress() Method

jQuery | keypress() Method: Learn about the jQuery keypress() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 19, 2022

keypress() Method

Events in jQuery are the actions that the user performs on the web page. It can be anything – related to mouse clicks, keyboard presses, etc. Using jQuery, we can control these events in the order we want and can also attach some custom functions to it if needed. That means, we can use predefined event methods for the actions and also define a function that gets fired when the event method is triggered. Overall, this makes the website more dynamic on the user's end. Let's learn about the keypress() method here.

The keypress() method is a built-in jQuery method. It gets triggered whenever the user presses any key on the keyboard. Therefore, it executes the attached function, if any, when it detects any key pressed for the selected element. Generally, the keypress event is used along with the keyup event or keydown event to show some result. This method is similar to the keydown() method in jQuery, but keypress() method doesn't check some specific keys when pressed like – ESC, CTRL, ALT, SHIFT, etc. To check these keys, one must use the keydown() method.

keypress() Method Syntax

$('selector').keypress();
$('selector').keypress(function);

It takes one optional parameter – function. The function is the custom function that can be defined to do some tasks when this method gets triggered.

The below example shows how the keypress() method gets triggered when the user starts typing in the given input box.

jQuery keypress() Method Example

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  
  <body>
    <h2>jQuery Event - KeyPress</h2>
    <p>Get to know when any key is pressed.</p>
    <hr>
    <h4>Press Any Key</h4>
    <input type="text"><br><br>
    <hr>
    <ol></ol>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('input').keypress(function(){
            $('ol').append('<li>Key Pressed</li>');
        });
    });    
  </script>
</html>

Output:

Example 1: jQuery keypress() Method



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.