Home >Web Front-end >JS Tutorial >How to Manually Trigger an Onchange Event After Setting Input Value with a Widget?

How to Manually Trigger an Onchange Event After Setting Input Value with a Widget?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-26 09:26:16297browse

How to Manually Trigger an Onchange Event After Setting Input Value with a Widget?

How to Trigger an Onchange Event Manually When Setting Input Value via a Widget

When dynamically updating the value of a date-time textfield through a calendar widget, the need arises to trigger an onchange event manually. This is because the widget's value assignment, like document.getElementById('datetimetext').value = date_value;, circumvents the default event trigger.

The solution lies in manually dispatching a custom event object, as suggested by MDN:

// Assuming we're listening for e.g. a 'change' event on `element`

// Create a new 'change' event
var event = new Event('change');

// Dispatch it.
element.dispatchEvent(event);

By dispatching this custom event, you can manually trigger the onchange event handler, allowing you to reset other fields in the page as needed.

The above is the detailed content of How to Manually Trigger an Onchange Event After Setting Input Value with a Widget?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn