Definitive way to trigger keypress events with jQuery
I've read all the answers on to this questions and none of the solutions seem to work.
Also, I am getting the vibe that triggering keypress with special characters does not work at all. Can someone verify who has done this?
Solution 1:
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);
Solution 2:
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.)
Solution 3:
The real answer has to include keyCode:
var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
e.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.
Solution 4:
If you're using jQuery UI too, you can do like this:
var e = jQuery.Event("keypress");
e.keyCode = $.ui.keyCode.ENTER;
$("input").trigger(e);
Solution 5:
I made it work with keyup.
$("#id input").trigger('keyup');