Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definitive way to trigger keypress events with jQuery

People also ask

How do you trigger key events?

HTML and CSS layout: In the given layout, when an input is made in the field, the keyCode value will be logged in the box. The events related to keypresses are as follows : keydown: This event is triggered when a key is pressed down. keypress: This event is triggered when a key is pressed.

How does jQuery detect keyboard press?

jQuery | keypress() The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.

Is jQuery keypress deprecated?

Probably false positive JS inspection: jQuery keyup(), keydown(), keypress() are marked as deprecated.

What is the difference between jQuery Change () and keypress () events?

The change event occurs if the value has been changed when the element loses focus. The keypress event occurs every time you press down and release a (non control) key.


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 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.


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);

I made it work with keyup.

$("#id input").trigger('keyup');