How do I programmatically trigger an “input” event without jQuery?

前端 未结 4 1557
攒了一身酷
攒了一身酷 2020-11-27 18:33

I installed an event handler on an input using

var element = document.getElementById(\'some-input\');
element.addEventListener(\'input\', functi         


        
相关标签:
4条回答
  • 2020-11-27 19:22

    The proper way to trigger an event with plain JavaScript, would be to create an Event object, and dispatch it

    var event = new Event('input', {
        bubbles: true,
        cancelable: true,
    });
    
    element.dispatchEvent(event);
    

    FIDDLE

    This is not supported in IE, for that the old-fashioned way still has to be used

    var event = document.createEvent('Event');
    event.initEvent('input', true, true);
    
    elem.dispatchEvent(event);
    
    0 讨论(0)
  • 2020-11-27 19:24

    If you are using react, following will work:

    const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
    const prototype = Object.getPrototypeOf(this.textInputRef);
    const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
    if (valueSetter && valueSetter !== prototypeValueSetter) {
        prototypeValueSetter.call(this.textInputRef, 'new value');
    } else {
        valueSetter.call(this.textInputRef, 'new value');
    }
    this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));
    
    0 讨论(0)
  • 2020-11-27 19:25

    Try this code

    var event = document.createEvent('Event');
    event.initEvent('input', true, true);
    
    elem.dispatchEvent(event);
    
    0 讨论(0)
  • 2020-11-27 19:31

    This answer is buried in a comment, but is more concise than the most popular answer, so I'm gonna give it a shot as its own answer. Hope it helps.

    element.dispatchEvent(new Event('input', { bubbles: true }));
    

    Or maybe even just...

    element.dispatchEvent(new Event('input'));
    
    0 讨论(0)
提交回复
热议问题