1

I'm developing an autofill extension. I want to fill an input field with a value, example value = "12345", and then trigger the equivalent of a jQuery $(element).change(), but in pure JavaScript/DOM.

I've tried dispatching the change method,

document.querySelector("input[name=inputIWantToChange]").dispatchEvent(new Event("change"));

but the behavior is different than that of

$("[name=inputIWantToChange]").change()
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Fernando Bessa
  • 785
  • 1
  • 4
  • 10
  • Does this answer your question? [jQuery change method in vanilla JavaScript?](https://stackoverflow.com/questions/24172963/jquery-change-method-in-vanilla-javascript) – EternalHour Mar 04 '20 at 17:19
  • @EternalHour That question is about attaching the event handler; this question is about dispatching (triggering) the event handler. – Heretic Monkey Mar 04 '20 at 17:21
  • "the behavior is different"; well, sure. jQuery does something different from the native DOM. That's kind of the point of jQuery. :). What is different and why is it a problem? – Heretic Monkey Mar 04 '20 at 17:27
  • Well in that case, this should cover it. [How to trigger event in JavaScript?](https://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript) or this [How can I trigger an onchange event manually?](https://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually). Plenty to choose from on this topic. – EternalHour Mar 04 '20 at 17:34
  • @EternalHour Agree wholeheartedly. Except those basically answer with code the OP already has, so I'd like to hear what their actual problem is, since apparently they are having a problem with it. Hard to tell what, without a response after a dozen minutes... – Heretic Monkey Mar 04 '20 at 17:39

1 Answers1

1

Looking at jQuery's source code, it would appear that jQuery works by invoking the handler that you have bound to the event (with a fake event that it creates) when you call change() - which means that you're going to have to find a way to be able to invoke a function, and also have the event invoke the same function. Consider the following:

var elem = document.querySelector("input[name=inputIWantToChange]");

elem.addEventListener("change", function (evt) {
    onElemChange() // Pass data from the event `evt` here, as needed
});

function onElemChange() {
    // Your handler method here
}

When you'd want to invoke a "change event" as you do with jQuery, you can then just call onElemChange with the information you'd have gotten from the event, assuming you'd want to use any of the information from the event.

megubyte
  • 1,549
  • 9
  • 15