Trigger a keypress/keydown/keyup event in JS/jQuery?

后端 未结 9 2080
长情又很酷
长情又很酷 2020-11-22 07:10

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,

相关标签:
9条回答
  • 2020-11-22 07:31

    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

    0 讨论(0)
  • 2020-11-22 07:31

    You're now able to do:

    var e = $.Event("keydown", {keyCode: 64});
    
    0 讨论(0)
  • 2020-11-22 07:38

    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);
    
    0 讨论(0)
  • 2020-11-22 07:46

    For typescript cast to KeyboardEventInit and provide the correct keyCode integer

    const event = new KeyboardEvent("keydown", {
              keyCode: 38,
            } as KeyboardEventInit);
    
    0 讨论(0)
  • 2020-11-22 07:46

    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 讨论(0)
  • 2020-11-22 07:49

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题