Skip to content Skip to sidebar Skip to footer

Why Onchange Function Not Called When Checkbox Changed Using Checked Property

Checkbox is handled using another button. If I directly click on checkbox then the onchange triggers. But when I change the check box using button, onchange(i.e. show() method) is

Solution 1:

Setting the checked property of a checkbox doesn't trigger a change event from that checkbox. You will have to dispatch it yourself:

y.addEventListener('click', (e) => {
  // toggle the checkbox
  x.checked = !x.checked;
  // and manually dispatch a change event on the checkbox
  let change = new Event('change');
  x.dispatchEvent(change);
})

x.addEventListener('change', (e) => {
  console.log(x.checked);
})
<input type='checkbox' name='xyz' id='x' />

<br>

<button id='y'>Toggle Checkbox</button>

Post a Comment for "Why Onchange Function Not Called When Checkbox Changed Using Checked Property"