'Converting jQuery .change() to plain JavaScript/DOM

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()


Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 megubyte