10

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?

3 Answers 3

20

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>

Sign up to request clarification or add additional context in comments.

Comments

1

There are two ways of achieving this:

First way, as Josh Crozier stated, is to change the checked attribute and after that, dispatching the desired event. For instance:

// To toggle the checked state (true -> false, false -> true):
const checkBox = document.getElementById('mycheckbox');
checkBox.checked = !checkBox.checked;
checkbox.dispatchEvent(new Event('change'));

However, that way you would need to know what kind of event you're listening to. For example, in this case, you could be listening to the input event rather than the change event, and it would not work. That is why I prefer this alternative:

// To toggle the checked state (true -> false, false -> true):
const checkBox = document.getElementById('mycheckbox');
checkBox.click();

// ...Or if you want to always check (? -> true):
const checkBox = document.getElementById('mycheckbox');
if (!checkBox.checked) {
    checkBox.click();
}

// ...Or to always uncheck (? -> false):
const checkBox = document.getElementById('mycheckbox');
if (checkBox.checked) {
    checkBox.click();
}

The click() function simulates a click made by the user, so it will trigger whatever event is associated with the checkbox input. I also think it is more straight forward.

Comments

-1

You might want to place it inside of a window.onload to make sure the dom is ready, $(document).ready equivalent without jQuery

var checkbox = document.getElementById("test-check");
checkbox.addEventListener("change", checked, false);

function checked(e) {
  console.log(e.target.checked)
}

var event = new Event('change');
checkbox.checked = !checkbox.checked;
checkbox.dispatchEvent(event);
<span>
  <input type="checkbox" id="test-check">
 Test
</span>

Also you have some alternatives to the change event

Documentation

4 Comments

@TeChn4K How is this off the subject? It's literally the answer to the question...
He wants to know how to handle change done with programmatic checkbox.value = <any_bool>. Sorry but your answer is not working...
@TeChn4K The question has been edited after answer has been submitted if you look at the original title 'Event When Checkbox is changed via Javascript' it's not a case my answer being 'off the subject' it's subject changing after submission. I have updated it based on your comments
Title have been reformulated, but question didn't change at all. Stop being like this. Btw, your updated answer still doesn't work ... You listen for change event, but you dispatch a check event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.