Trigger “onchange” event

后端 未结 4 931
日久生厌
日久生厌 2020-12-03 03:20

The \"onchange\" event is triggered only when the USER enters some value. Why isn\'t possible to fire the event when I change the value automatically via Javascript ? Is the

相关标签:
4条回答
  • 2020-12-03 03:58

    The vast majority of the time, you don't want an event to be fired when you change the value with code. In those cases where you do, you can fire a synthetic event on modern browsers via dispatchEvent. More here.

    So in your specific example:

    input.value = "Another example";
    var event = document.createEvent("UIEvents"); // See update below
    event.initUIEvent("change", true, true);      // See update below
    input.dispatchEvent(event);
    

    Live demo

    Update: As Benjamin noted, since the above was written, initUIEvent has been replaced with the UIEvent constructor, so that would be:

    input.value = "Another example";
    var event = new UIEvent("change", {
        "view": window,
        "bubbles": true,
        "cancelable": true
    });
    input.dispatchEvent(event);
    

    Live demo

    Alternately, you can always just call whatever function you've bound to the change event directly, which is usually what I'd do. But sometimes you want to use actual events (for instance, when using the observer pattern) and ensure that anyone who is listening for the change is notified.

    0 讨论(0)
  • 2020-12-03 04:09

    The code of Crowder only gave me an TypeError (Not enough arguments to UIEvent.initUIEvent). Change it to this:

    input.value = "Another example";
    var event = document.createEvent("UIEvents");
    event.initUIEvent("change", true, true, window, 1);
    input.dispatchEvent(event);
    

    and it works.

    0 讨论(0)
  • 2020-12-03 04:12

    If you are changing the value progammatically, you already know when this occurs, what's to say you can't call your own method, (the same perhaps that is called from the actual trigger event handler) when you change the value?

    EDIT: otherwise, if you specifically need the actual Fire to occur, you can manually dispatch the event yourself too.

    0 讨论(0)
  • 2020-12-03 04:16

    Note that initUIEvent has been deprecated and removed from Web Standards as stated: developer.mozilla.org/en-US/docs/Web/API/UIEvent/initUIEvent

    This is the same except that it doesn't use initUIEvent:

    input.value = 'Another example';
    var event = new UIEvent('change', {
        'view': window,
        'bubbles': true,
        'cancelable': true
    });
    input.dispatchEvent(event);
    
    0 讨论(0)
提交回复
热议问题