Definitive way to trigger keypress events with jQuery
If you want to trigger the keypress or keydown event then all you have to do is:
var e = jQuery.Event("keydown");e.which = 50; // # Some key code value$("input").trigger(e);
Slightly more concise now with jQuery 1.6+:
var e = jQuery.Event( 'keydown', { which: $.ui.keyCode.ENTER } );$('input').trigger(e);
(If you're not using jQuery UI, sub in the appropriate keycode instead.)
The real answer has to include keyCode:
var e = jQuery.Event("keydown");e.which = 50; // # Some key code valuee.keyCode = 50$("input").trigger(e);
Even though jQuery's website says that which and keyCode are normalized they are very badly mistaken. It's always safest to do the standard cross-browser checks for e.which and e.keyCode and in this case just define both.