I need to know when a checkbox has been changed by Javascript using pure javascript.
I have setup an 'onchange' event that successfully executes when the user changes the checkbox but this doesn't work when another JS function changes it using code like the following:
document.getElementById('mycheckbox').checked = true;
Is it possible to fire an event using pure JavaScript when JS either checks or unchecks a checkbox?
You can create a change
event with the document.createEvent
/initEvent
methods and then use the dispatchEvent
method to dispatch the event from the specified checkbox
element.
var event = document.createEvent("HTMLEvents");
event.initEvent('change', false, true);
checkbox.dispatchEvent(event);
This will allow you to programmatically change the checked
property of the element and then trigger a change
event that will thereby fire the event listeners.
Here is a basic example:
var checkbox = document.querySelector('[type="checkbox"]');
var button = document.querySelector('button');
// Event Listener:
checkbox.addEventListener('change', function(event) {
alert(event.target.checked);
});
// Programmatically change the `checked` property:'
button.addEventListener('click', function() {
checkbox.checked = !checkbox.checked;
triggerEvent(checkbox, 'change');
});
function triggerEvent(element, eventName) {
var event = document.createEvent("HTMLEvents");
event.initEvent(eventName, false, true);
element.dispatchEvent(event);
}
<input type="checkbox" />
<button>Programmatically trigger 'change' event</button>
As an alternative, you can also use the Event()
constructor, however it has less browser support.
var event = new Event('change');
checkbox.dispatchEvent(event);
Here is an example:
var checkbox = document.querySelector('[type="checkbox"]');
var button = document.querySelector('button');
// Event Listener:
checkbox.addEventListener('change', function(event) {
alert(event.target.checked);
});
// Programmatically change the `checked` property:'
button.addEventListener('click', function() {
checkbox.checked = !checkbox.checked;
triggerEvent(checkbox, 'change');
});
function triggerEvent (element, eventName) {
var event = new Event(eventName);
element.dispatchEvent(event);
}
<input type="checkbox" />
<button>Programmatically trigger 'change' event</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With