jQuery .keypress() event

Syntax and Description


.keypress(handler)          
.keypress()

handler is a function to execute each time the event is triggered. Return value is the jQuery object, for chaining purposes.

.keypress binds an event handler to the keypress JavaScript event, or trigger that event on an element.

.keypress(handler) is a shortcut for .bind('keypress', handler). .keypress() is a shortcut for .trigger('keypress').

We can trigger the event manually when another element is clicked.


$('#other').click(function() {
    $('#target').keypress();
});

Convert key code to char

The following code converts key code to char in keypress event handler.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){<!--from w w w . j av  a2s  . com-->
        $("input").keypress(function (e) {
            var c = String.fromCharCode(e.which);
            $("p").append($("<span/>")).children(":last").append(document.createTextNode(c));
            $("div").text(e.which);
        });
    });
    </script>
  </head>
  <body>
    <body>
     <input type="text" />
      <p>Add text - </p>
      <div></div>

    </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities