.keypress()

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. jav a  2 s  .c  om-->
        $("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

The code above generates the following result.

.keypress()
Home »
  Javascript Tutorial »
    jQuery Reference »
      Event
Javascript Tutorial Event
Event
Event attributes
event.keycode
event.clientX/clientY
pageX/pageY
Cancel event
Event target
bind
.blur()
.change()
.click()
.error()
.dblclick()
.delegate()
.die()
.focus()
.hover()
.keydown()
.keypress()
.keyup()
.live()
.load()
.mousedown()
.mouseenter()
.mouseleave()
.mousemove()
.mouseover()
.mouseout()
.mouseup()
.off()
.on()
.one()
.ready()
.resize()
.scroll()
.select()
.submit()
.toggle()
.trigger()
.triggerHandler()
.unbind()
.undelegate()
.unload()