Explain Codes LogoExplain Codes Logo

Trigger Change event when the Input value changed programmatically?

javascript
event-dispatch
javascript-features
browser-compatibility
Nikita BarsukovbyNikita Barsukov·Nov 16, 2024
TLDR

Trigger a change event after updating an input's value by crafting a new Event('change') and dispatching it using .dispatchEvent().

let input = document.querySelector('input'); input.value = 'newVal'; // Update value here, fellows input.dispatchEvent(new Event('change')); // It's showtime, post a change event

Unraveling the event dispatch mystery

Event dispatching is all about triggering events through scripts. If you're thirsty for user interaction but your cup is limited to programmatic value changes, dispatchEvent() is your tall drink of water.

Usually, a change event occurs when a user interacts with an input element altering its value. But, when you use JavaScript to do an undercover operation and change the input value, the change event isn't triggered automatically.

Dealing with the relics: Older browsers

The smooth sailing of dispatchEvent() in modern browsers could hit rough waters if your project needs to support old browsers (like IE 10 and below). That's when we call in the feature detection troops!

if (typeof document.body.dispatchEvent === 'function') { el.dispatchEvent(new Event('change')); // Unleash the Kraken, i.e., dispatch event } else { // Dispatch event, old school style. IE 10 and below, you're welcome! var event = document.createEvent('HTMLEvents'); event.initEvent('change', false, true); el.dispatchEvent(event); }

A walk down the jQuery lane

For projects where jQuery is your friend, you can trigger a change event right after fiddling with the input field. The .trigger() method lets you shout 'change' from the rooftops like a town crier in old England:

$('input').val('newVal').trigger('change'); // 'Change! Hear ye, hear ye!'

This method helps you keep your JavaScript separate from your HTML, making it easy to maintain code. More code readability, less stress! Isn't that neat?

Keeping a constant eye with 'input' event

Replace 'change' with the 'input' event if your project demands real-time updates. The moment the user types or you change the value programmatically — boom! You've got an event.

input.addEventListener('input', function(event) { console.log('Input changed to: ', event.target.value); // spotted the change, *winks* });

Value setters, assemble!

In high-demand situations, call upon Object.getOwnPropertyDescriptor to override the default setter for the value property on input elements. Curious? Check out that fancy trick here.