Search code examples
javascriptcheckboxdispatchevent

How can I dispatch a checkbox click programmatically?


I've tried several javascript functions here and there but it seems that none of them worked for me. What I'm doing is displaying a tower, that has as many stages as the user wishes. This is basically creating HTML tags using Js for every stage and the last one is a checkbox. The thing I'd like to do is that when I click on a checkbox, all the other ones that are over this one would check programmatically also. So this is what I did:

    let event = new Event('click');

    //Here, q is the maximum stage that the user set.

    document.addEventListener('click', function(e) {
        let readStr = e.target.id;
        if (readStr.startsWith("checkboxFan") && e.isTrusted) {
            for (let r=parseFloat(readStr.substr(-1))+1; r<=q; r++) {
                document.getElementById("checkboxFan"+r).dispatchEvent(event);
            }
        }
    }, false);

And it's finding the IDs well and doing what I want, but the dispatchEvent isn't working as expected. In fact, it's not working at all. Also, the "click()" function works but the isTrusted is triggered, which is not what I want because the checkbox has to be clicked by the user.

Any solutions?


Solution

  • I've written some code based on your description.
    https://stackblitz.com/edit/js-poevax?file=index.js

    document.addEventListener(
      "click",
      function(e) {
        let readStr = e.target.id;
        if (readStr.startsWith("checkboxFan") && e.target.checked) {
          for (let r = parseFloat(readStr.substr(-1)) + 1; r <= q; r++) {
            document.getElementById("checkboxFan" + r).checked = true;
          }
        }
      },
      false
    );
    

    You should check this page.
    Input Checkbox checked Property

    cheers!