Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger an event when a checkbox is changed programmatically via JavaScript

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?

like image 517
Ben Tideswell Avatar asked Feb 01 '17 13:02

Ben Tideswell


1 Answers

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>
like image 58
Josh Crozier Avatar answered Nov 08 '22 16:11

Josh Crozier