jeudi 22 octobre 2020

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 much stages as the user wish. This is basically creating html tags using Js for every stages 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 ?

Many thanks, have a nice day !




Aucun commentaire:

Enregistrer un commentaire