Search code examples
javascriptjquerykeypressjquery-events

Simulate keypress with jQuery on form element


I'm trying to simulate a keypress with the below code...

jQuery('input[name=renameCustomForm]').live('keyup', function (e) {
      console.log('pressed');
});
jQuery('body').click(function (e) {
        console.log(jQuery('input[name=renameCustomForm]'));
        var press = jQuery.Event("keypress");
        press.which = 13;
        jQuery('input[name=renameCustomForm]').trigger(press);
 });

I got this code from other posts on SO, but it doesn't work. Anyone know why?

Update

Fixed it... it appears triggering "keypress" doesn't automatically trigger "keyup"


Solution

  • Normally, when a user adds something to an inout field, the following events occur:

    1. keydown (once).
    2. keypress (at least once, additional events uccur while the key is pressed down)
    3. keyup (once)

    When a key event is simulated, it's not necessary that all events occur in this order. The event is manually dispatched, so the normal event chain isn't activated.

    Hence, if you manually trigger the keypress event, the keyup event won't be fired.