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.