jQuery API

.keypress()

.keypress( handler(eventObject) ) Returns: jQuery

Description: Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element.

  • version added: 1.0.keypress( handler(eventObject) )

    handler(eventObject)A function to execute each time the event is triggered.

  • version added: 1.4.3.keypress( [eventData], handler(eventObject) )

    eventDataA map of data that will be passed to the event handler.

    handler(eventObject)A function to execute each time the event is triggered.

  • version added: 1.0.keypress()

Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.

This method is a shortcut for .bind("keypress", handler) in the first two variations, and .trigger("keypress") in the third.

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except in the case of key repeats. If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character. In addition, modifier keys (such as Shift) trigger keydown events but not keypress events.

A keypress event handler can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

For example, consider the HTML:

<form>
  <fieldset>
    <input id="target" type="text" value="Hello there" />
  </fieldset>
</form>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to the input field:

$("#target").keypress(function() {
  alert("Handler for .keypress() called.");
});

Now when the insertion point is inside the field, pressing a key displays the alert:

Handler for .keypress() called.

The message repeats if the key is held down. To trigger the event manually, apply .keypress() without an argument::

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

After this code executes, clicks on Trigger the handler will also alert the message.

If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the document object. Because of event bubbling, all key presses will make their way up the DOM to the document object unless explicitly stopped.

To determine which character was entered, examine the event object that is passed to the handler function. While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the character code.

Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.

Example:

Show the event object when a key is pressed in the input. Note: This demo relies on a simple $.print() plugin (http://api.jquery.com/scripts/events.js) for the event object's output.

<!DOCTYPE html>
<html>
<head>
  <style>
fieldset { margin-bottom: 1em; }
input { display: block; margin-bottom: .25em; }
#print-output {
  width: 100%;
}
.print-output-line {
  white-space: pre;
  padding: 5px;
  font-family: monaco, monospace;
  font-size: .7em;
}

</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <form>
  <fieldset>
    <label for="target">Type Something:</label>
    <input id="target" type="text" />
  </fieldset>
</form>
<button id="other">
  Trigger the handler
</button>
<script src="http://api.jquery.com/scripts/events.js"></script>
<script>
var xTriggered = 0;
$("#target").keypress(function(event) {
  if ( event.which == 13 ) {
     event.preventDefault();
   }
   xTriggered++;
   var msg = "Handler for .keypress() called " + xTriggered + " time(s).";
  $.print( msg, "html" );
  $.print( event );
});

$("#other").click(function() {
  $("#target").keypress();
});</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .keypress() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .keypress()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • Martin M.

    Can someone please explain to me what event.keyCode is for anyway?
    In this api docs entry it is said that jQuery normalizes every character input to the event.which attribute. However, in the example event.keyCode is used. Why is that?

    • Gmchad

      I’m experiencing a browser problem when using Keypress to capture the Enter key (13) when posting two separate input/submit forms on the same page calling different actions. In some browsers (like Firefox), the two instances of keypress capturing the Enter key and doing something different seem to work fine; versions of IE however only capture the first instance of the keypress assignment; further input fields listening for the Enter key fail as it believes the first instance is still in “focus”.

      Has anyone had experience with this problem? I’m stuck getting this to work consistently across browsers, IE6 being a necessity for the project I’m working on.

  • http://lmframework.com/blog/about David Semeria

    Keypress is useful because it captures modifier keys (ctrl, alt, etc). However, it doesn't work in Chrome. Keydown does work in Chrome, but doesn't capture modifiers. Below is a little fragment which allows modifiers to be caught with keydown.

    $(document).ready( function(){  modifier = function() {    var prevKey;    var f = function(key) {      var r = prev_key;      prevKey = key;      if (r == 17) return 'ctrl';      if (r == 18) return 'alt';      if (r == 27) return 'esc';    };    return f;  }();
    
      $("html").keyup( modifier );	   $("html").keydown( keyDown );});
    
    function keyDown(ev){  switch(modifier(ev.keyCode)){    case 'ctrl':       switch(ev.keyCode){        case 68: // ctrl + D                 return false;       }    case 'alt':      switch(ev.keyCode){        case 68: // alt + D                 return false;      }  }}
  • http://keul.it Anonymous

    The is no way, with keypress, to know what is the new value that a textarea will get?
    Using the keyup is not a good choice, as it is fired after keypress…

    • Travis

      var newValue = textarea.value + String.fromCharCode(event.which);

      • http://keul.it Anonymous

        This is false. What if I’m inserting a character inside the textarea, not at the end?

        • Travis

          ah, great point!

    • Ark

      Try setTimeout(function(){}) – it runs Async, so value of texarea willbe new one

      $(“.TextBox”).keypress(function(e){
      var timeout = null;
      var val = $(this);
      timeout = setTimeout(function(){alert(val.val());}, 500);
      });

  • Travis

    The example should not only use event.which but it should also test event.which === 13 since it isn't a string object.

    • Travis

      Here’s an example:
      http://jsbin.com/abiri3/edit

      • Travis

        Also, another quirk, when TAB is pressed:
        which: 0,
        keyCode: 9,

        whaaa?? Shouldn't which be 9 too?

        • Rybadour

          Not in IE, use keyCode in IE, and which in every other browser.

          • Dan

            What is the point of having 'which' (which the docs state: “While browsers use differing attributes to store this information, jQuery normalizes the .which attribute so we can reliably use it to retrieve the character code.”) if you still have to do browser-specific messing about?

            This smells like a bug!

          • http://www.learningjquery.com/ Karl Swedberg

            It is a bug, and we're targeting a fix for jQuery 1.4.3.

          • Mail Temc

            Has this been fixed ? If not, is there a link to the ticket ?

  • http://twitter.com/jkarmel jkarmel

    When I press the delete key the keypress event is not activated. What gives?

    • Travis

      it should have a value of 46 (on Windows):
      http://jsbin.com/abiri3/11

      • Travis

        It looks like IE has issues with keys like DELETE and TAB

        • Kasper

          Chrome doesn't register delete too! :(

      • http://travis.servebeer.com/blog.net/ travis

        46 is the value for '.' the correct ascii value is 127, maybe that will get fixed in 1.4.3.

  • http://twitter.com/Increazon John Macklein

    not working it. developers of JQ – are dumb asses. i going to prototype – you suck!

  • http://pulse.yahoo.com/_B2JWWB4KSFEP4OCEWWF6ELVMKU brahma n

    What is “Escape” key press Number in Chrome Browser

  • Ark

    Try setTimeout(function(){}) – it runs Async, so value of texarea willbe new one

    $(“.TextBox”).keypress(function(e){
    var timeout = null;
    var val = $(this);
    timeout = setTimeout(function(){alert(val.val());}, 500);
    });

  • http://www.orbital.co.nz Johan

    If you are having problems with keyboard events not working consistently across browser try binding to document.documentElement instead of body or window:

    http://jqueryfordesigners.com/adding-keyboard-n…

  • InAme19

    I have a question,
    I use a event keypress on $(“body”) and an other on a div $(“.test”). When I click on the div test I have the keypress of this div but I have the keypress of $(“body”) too… How I can delete the parents's keypress ?
    Thanks for advance

    • Vallab

      You can cancel the parent bubbling by adding this code to function
      if (!e) var e = window.event;
      e.cancelBubble = true;
      if (e.stopPropagation)
      e.stopPropagation();

      • Mail Temc

        jQuery takes care of browser variations in event and event values.

        Just call e.stopPropagation();

        $(something).someEvent(function(e){
        e.stopPropagation();

        // Do stuff
        });

  • mark

    Be careful with the escape key when loading data using the $.get() function. It ends up canceling the request, so just call preventDefault() before sending any data requests

  • Kamran Ali

    how to deal ctrl+c and ctrl+v in this event..

  • http://twitter.com/Flipcube Flipcube

    I need cancel character input, if this is not numer. I was tried to return false, like this:
    if ((event.which < 48 || event.which > 57) && event.which != 190)
    return false;

    But unwanted characters appears anyway. What shall I do?

    • AK

      Just do what they did in the demo:

      event.preventDefault();

      But, be sure to check “event.which”, not “event.keyCode” like they did. It isn't cross-browser supported.

  • http://twitter.com/jcubic Jakub Jankiewicz

    If you want to use arrows, delete, backspace keys in Chrome you must use keydown. keypress on these keys work only in Firefox and Opera.

  • http://twitter.com/jcubic Jakub Jankiewicz

    If you want to use arrows, delete, backspace keys in Chrome you must use keydown. keypress on these keys work only in Firefox and Opera.

  • II ARROWS

    There is an easy way to trigger the event AFTER the character is being written to the control?
    For example, if I press “A” in a textbox, the browser first triggers the event so if I want to use the textbox value, it is the one before the event.

    • http://webintegreat.myopenid.com/ WebIntegreat

      You should use keyup instead of keypress.

  • Karthimailu

    how to press keyboard left key in function

  • Boozker

    When working with keypress, keyup, etc, i find it a lot easier to work with:
    http://oscargodson.com/labs/jk…/

  • Martin M.

    @foo You shouldn't use keycode anyway. jQuery normalizes (across browsers) to the .which attribute.

  • Ark

    use live() to bind event of generated elems –

    $('input').live('click', function() {

    alert(e.keyCode);

    });