229

What is the best way to simulate a user entering text in a text input box in JS and/or jQuery?

I don't want to actually put text in the input box, I just want to trigger all the event handlers that would normally get triggered by a user typing info into a input box. This means focus, keydown, keypress, keyup, and blur. I think.

So how would one accomplish this?

10 Answers 10

274

You can trigger any of the events with a direct call to them, like this:

$(function() {
    $('item').keydown();
    $('item').keypress();
    $('item').keyup();
    $('item').blur();
});

Does that do what you're trying to do?

You should probably also trigger .focus() and potentially .change()

If you want to trigger the key-events with specific keys, you can do so like this:

$(function() {
    var e = $.Event('keypress');
    e.which = 65; // Character 'A'
    $('item').trigger(e);
});

There is some interesting discussion of the keypress events here: jQuery Event Keypress: Which key was pressed?, specifically regarding cross-browser compatability with the .which property.

4
  • 5
    or $('item').trigger('keypress', {which: 'A'.charCodeAt(0)});
    – Bob Stein
    Commented Jun 8, 2017 at 17:37
  • 2
    @ebynum Can you write some code with Javascript (no jquery).
    – Chris P
    Commented Nov 22, 2018 at 13:36
  • 2
    If you need Ctrl: ctrlKey: true, also: shiftKey, altKey Commented Dec 6, 2018 at 15:44
  • 1
    KeyboardEvent(typeArg, KeyboardEventInit)
    – Joshua
    Commented Dec 4, 2021 at 21:26
118

You could dispatching events using Event and KeyboardEvent like this:

el.dispatchEvent(new Event('focus'));
el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
4
  • 7
    or el.dispatchEvent(new Event('keypress', {keyCode: 'a'}))
    – cuzox
    Commented May 10, 2018 at 20:51
  • 4
    @Cuzox why not use KeyboardEvent? It autofills values like shiftKey and it is the correct way. Also, you put a string in keyCode, that is wrong.
    – SuperOP535
    Commented Sep 13, 2018 at 14:16
  • 14
    If you need Ctrl: el.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 70, ctrlKey: true })); (This will cause a shortcut Ctrl + F) Commented Dec 6, 2018 at 15:43
  • 1
    KeyboardEvent(typeArg, KeyboardEventInit)
    – Joshua
    Commented Dec 4, 2021 at 21:27
35

To trigger an enter keypress, I had to modify @ebynum response, specifically, using the keyCode property.

e = $.Event('keyup');
e.keyCode= 13; // enter
$('input').trigger(e);
3
  • 3
    keydown event isn't being caught, or am I doing something wrong here? fiddle.jshell.net/Palestinian/8d8J9
    – Omar
    Commented Jul 21, 2013 at 0:27
  • @cloak: it works. Check my comment here for a complete selector to fix asp.net controls: codeproject.com/Tips/269388/… Make sure you call it after you insert anything in the dom if using Ajax. Commented Oct 16, 2015 at 23:32
  • Warning: keyCode property is deprecated; you should use KeyboardEvent.key instead, if available.
    – john Smith
    Commented Feb 7 at 8:42
29

You can achieve this with: EventTarget.dispatchEvent(event) and by passing in a new KeyboardEvent as the event.

For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))

Working example:

// get the element in question
const input = document.getElementsByTagName("input")[0];

// focus on the input element
input.focus();

// add event listeners to the input element
input.addEventListener('keypress', (event) => {
  console.log("You have pressed key: ", event.key);
});

input.addEventListener('keydown', (event) => {
  console.log(`key: ${event.key} has been pressed down`);
});

input.addEventListener('keyup', (event) => {
  console.log(`key: ${event.key} has been released`);
});

// dispatch keyboard events
input.dispatchEvent(new KeyboardEvent('keypress',  {'key':'h'}));
input.dispatchEvent(new KeyboardEvent('keydown',  {'key':'e'}));
input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));
<input type="text" placeholder="foo" />

MDN dispatchEvent

MDN KeyboardEvent

2
  • 1
    the code snippet doesn't work on Chrome - do you know why..? Commented Apr 6, 2021 at 10:26
  • 1
    Hmn, for me it works in chrome, version 121.0.6167.161
    – john Smith
    Commented Feb 7 at 8:53
28

Here's a vanilla js example to trigger any event:

function triggerEvent(el, type){
if ('createEvent' in document) {
        // modern browsers, IE9+
        var e = document.createEvent('HTMLEvents');
        e.initEvent(type, false, true);
        el.dispatchEvent(e);
    } else {
        // IE 8
        var e = document.createEventObject();
        e.eventType = type;
        el.fireEvent('on'+e.eventType, e);
    }
}
2
  • 10
    Can you furnish a few examples of usage? How would your function be used to send a keycode?
    – Mac
    Commented Feb 14, 2017 at 14:52
  • 10
    The source code for this post can be found at the following link which includes documentation: plainjs.com/javascript/events/trigger-an-event-11 Commented Sep 12, 2017 at 6:48
12

You're now able to do:

var e = $.Event("keydown", {keyCode: 64});
0
3

First of all, I need to say that sample from Sionnach733 worked flawlessly. Some users complain about absent of actual examples. Here is my two cents. I've been working on mouse click simulation when using this site: https://www.youtube.com/tv. You can open any video and try run this code. It performs switch to next video.

function triggerEvent(el, type, keyCode) {
    if ('createEvent' in document) {
            // modern browsers, IE9+
            var e = document.createEvent('HTMLEvents');
            e.keyCode = keyCode;
            e.initEvent(type, false, true);
            el.dispatchEvent(e);
    } else {
        // IE 8
        var e = document.createEventObject();
        e.keyCode = keyCode;
        e.eventType = type;
        el.fireEvent('on'+e.eventType, e);
    }
}

var nextButton = document.getElementsByClassName('icon-player-next')[0];
triggerEvent(nextButton, 'keyup', 13); // simulate mouse/enter key press
3

For typescript cast to KeyboardEventInit and provide the correct keyCode integer

const event = new KeyboardEvent("keydown", {
          keyCode: 38,
        } as KeyboardEventInit);
1
  • The object is not matching the interface Commented Jan 14, 2021 at 12:37
2

I thought I would draw your attention that in the specific context where a listener was defined within a jQuery plugin, then the only thing that successfully simulated the keypress event for me, eventually caught by that listener, was to use setTimeout(). e.g.

setTimeout(function() { $("#txtName").keypress() } , 1000);

Any use of $("#txtName").keypress() was ignored, although placed at the end of the .ready() function. No particular DOM supplement was being created asynchronously anyway.

0

For me works only this

    const keyboardEvent = document.createEvent('KeyboardEvent');
    const m = keyboardEvent['initKeyboardEvent'] ? 'initKeyboardEvent' : 'initKeyEvent';
    keyboardEvent[m]('keydown', true, true, window, false, false, false, false, 40, 0);
    input.dispatchEvent(keyboardEvent);

and don't even ask me what happens here

Not the answer you're looking for? Browse other questions tagged or ask your own question.