281

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?

mkoryak
  • 57,086
  • 61
  • 201
  • 257
  • 15
    No you miss understood the concept. This is not how is it supposed to work. trigger will only call the event handler. It will not actually print the key. If you want to simulate the effect of printing the key, then just add the key to the input value and trigger the event at the same time. – Nadia Alramli May 07 '09 at 00:21
  • Interesting, i didnt know that. In that case, can you tell me if triggering the event will also trigger it for non-jquery libs. for example if i have a onKeydown set up in plain JS, will it capture my "fake" event? – mkoryak May 07 '09 at 16:10
  • 2
    yes, if there was an onkeydown='...' set up in plain js. It will be triggered by the fake event. I wasn't sure about it. But I made a quick test and it worked. – Nadia Alramli May 07 '09 at 18:06
  • 2
    @Nadia Thanks for that! I've read over all the answers wondering why things weren't working before realizing my expectations weren't correct. I suspect a lot of other people will have the same misconceptions. – mikemaccana Jan 14 '12 at 12:24
  • 3
    Two years later... reading the page it seem that the definitive way is : $('input#search').trigger($.Event( 'keydown', {which:$.ui.keyCode.ENTER, keyCode:$.ui.keyCode.ENTER})); – molokoloco May 16 '12 at 12:52

10 Answers10

382

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);
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
Nadia Alramli
  • 111,714
  • 37
  • 173
  • 152
  • 43
    the question is how to trigger, not how to capture – Chad Grant May 06 '09 at 22:48
  • 2
    I added an example for triggering the event – Nadia Alramli May 06 '09 at 23:05
  • 4
    Very nice answer. Worth noting that jQuery.Event is available for jQuery 1.3 or greater. It became relevant in this question: http://stackoverflow.com/questions/1823617/how-do-i-have-jquerys-autocomplete-plugin-display-its-dropdown-list-upon-page-lo/1823732 – artlung Dec 01 '09 at 03:07
  • 8
    This did not work for me with a jQuery UI slider. I had to set e.keyCode like OreiA's answer below. – crizCraig Feb 05 '11 at 20:35
  • 2
    fwiw, I had more success with 'keyup' for my application – mark Jan 09 '13 at 21:30
  • I had to do `e.keyCode = 32;` – Jazzy Mar 26 '15 at 18:53
  • The question I have is if I'm using Japanese input with Katakana keyboard I am seeing an incoming keydown event of 229. If I attempt to trigger a keypress in the input field using the key code of 229 nothing shows up in the input field. Is there a way to trigger international characters? – BrightIntelDusk Mar 16 '17 at 17:55
  • can we changed jQuery with $ character? – gumuruh Sep 20 '19 at 16:44
85

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

nickb
  • 2,870
  • 2
  • 25
  • 14
  • 4
    Just remember to substitute 'keyCode' for 'which' as well. – Richard Nienaber Apr 04 '12 at 21:25
  • Yes you must define which and keyCode to be safe (if the event listener checks for e.keyCode, it will only work if you define keyCode when creating the jQuery.Event object) – jackocnr Jun 26 '13 at 21:54
  • 1
    jQuery normalises which/keyCode so putting either in should do both. –  Jul 08 '13 at 14:12
  • +1 for the link to api.jquery.com; and current jQuery versions don't normalize which/keyCode, so you should supply both for safety – Victor Jun 12 '14 at 07:58
  • @Victor, current jQuery versions do exactly that: "The event.which property normalizes event.keyCode and event.charCode". You comment is a year old so maybe this has changed since then, but now no one will be confused by this. – Samuel Lindblom Sep 24 '15 at 07:01
  • 2
    @SamuelLindblom I should've written it more clear: jQuery don't normalize event properties passed via `.trigger(jQuery.Event('name', props))`. Look at example http://jsfiddle.net/9ggmrbpd/1/ - properties of triggered event are passed as is. Source code: https://github.com/jquery/jquery/blob/master/src/event.js#L739 – Victor Sep 24 '15 at 09:20
72

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.

Tomas
  • 3,054
  • 5
  • 27
  • 39
19

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);
Rodrigo Chacon
  • 311
  • 2
  • 5
7

I made it work with keyup.

$("#id input").trigger('keyup');
Abba
  • 519
  • 6
  • 17
4

Ok, for me that work with this...

var e2key = function(e) {
    if (!e) return '';
    var event2key = {
        '96':'0', '97':'1', '98':'2', '99':'3', '100':'4', '101':'5', '102':'6', '103':'7', '104':'8', '105':'9', // Chiffres clavier num
        '48':'m0', '49':'m1', '50':'m2', '51':'m3', '52':'m4', '53':'m5', '54':'m6', '55':'m7', '56':'m8', '57':'m9', // Chiffres caracteres speciaux
        '65':'a', '66':'b', '67':'c', '68':'d', '69':'e', '70':'f', '71':'g', '72':'h', '73':'i', '74':'j', '75':'k', '76':'l', '77':'m', '78':'n', '79':'o', '80':'p', '81':'q', '82':'r', '83':'s', '84':'t', '85':'u', '86':'v', '87':'w', '88':'x', '89':'y', '90':'z', // Alphabet
        '37':'left', '39':'right', '38':'up', '40':'down', '13':'enter', '27':'esc', '32':'space', '107':'+', '109':'-', '33':'pageUp', '34':'pageDown' // KEYCODES
    };
    return event2key[(e.which || e.keyCode)];
};

var page5Key = function(e, customKey) {
    if (e) e.preventDefault();
    switch(e2key(customKey || e)) {
        case 'left': /*...*/ break;
        case 'right': /*...*/ break;
    }
};

$(document).bind('keyup', page5Key);

$(document).trigger('keyup', [{preventDefault:function(){},keyCode:37}]); 
molokoloco
  • 4,504
  • 2
  • 33
  • 27
4

Of you want to do it in a single line you can use

$("input").trigger(jQuery.Event('keydown', { which: '1'.charCodeAt(0) }));
Ben
  • 13,297
  • 4
  • 47
  • 68
2

console.log( String.fromCharCode(event.charCode) );

no need to map character i guess.

Weldan Jamili
  • 63
  • 1
  • 9
2

In case you need to take into account the current cursor and text selection...

This wasn't working for me for an AngularJS app on Chrome. As Nadia points out in the original comments, the character is never visible in the input field (at least, that was my experience). In addition, the previous solutions don't take into account the current text selection in the input field. I had to use a wonderful library jquery-selection.

I have a custom on-screen numeric keypad that fills in multiple input fields. I had to...

  1. On focus, save the lastFocus.element
  2. On blur, save the current text selection (start and stop)

    var pos = element.selection('getPos')
    lastFocus.pos = { start: pos.start, end: pos.end}
    
  3. When a button on the my keypad is pressed:

    lastFocus.element.selection( 'setPos', lastFocus.pos)
    lastFocus.element.selection( 'replace', {text: myKeyPadChar, caret: 'end'})
    
Flint O'Brien
  • 526
  • 6
  • 8
1

It can be accomplished like this docs

$('input').trigger("keydown", {which: 50});
Joe
  • 879
  • 3
  • 14
  • 37
Bek
  • 3,157
  • 1
  • 17
  • 28
  • 1
    This does not seem to work because this uses the extraParameters argument which does not set anything inside the event argument but adds extra arguments to the event handler callback. –  Jun 06 '16 at 16:08
  • 1
    Not a valid solution – Entwickler Nov 03 '16 at 15:10