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

后端 未结 9 2081
长情又很酷
长情又很酷 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:49

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

    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.

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

    You could dispatching events like

    el.dispatchEvent(new Event('focus'));
    el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));
    
    0 讨论(0)
提交回复
热议问题