Why onchange function not called when checkbox changed using checked property

后端 未结 1 477
闹比i
闹比i 2021-01-26 20:24

Checkbox is handled using another button.

  1. If I directly click on checkbox then the onchange triggers.

  2. But when I change the check box using butt

相关标签:
1条回答
  • 2021-01-26 21:00

    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>

    0 讨论(0)
提交回复
热议问题