简体   繁体   中英

Any way of triggering a event in Javascript when Html checkbox gets unchecked?

A pretty basic problem but can't find any viable solution. I have this event listener:

div.addEventListener('change', function () {
    const checkBox = event.target
    const checked = checkBox.checked
    let checkBoxName = checkBox.name

    if (checked) {
        for(ii = 0; ii < IdOfLayers.length; ii++) {
            if(checkBoxName == IdOfLayers[ii]) {
                checkBoxName = 0
            }
        }
        IdOfLayers.push(checkBoxName)
    }
    else if (document.getElementById(checkBoxName).checked == false) {
        //remove id from array
        console.log("unchecked triggered")
        for (i = 0; i < IdOfLayers.length; i++) {
            if (checkBoxName == IdOfLayers[i]) {
                x = IdOfLayers.splice(i,1,0)

            }
        }
    }
    console.log(IdOfLayers)
    let result = IdOfLayers.filter(word => word.length > 0)
    IdOfLayers = result
} )

As of now it detects whenever a checkbox is checked, then adds it to a array of checked checkboxes, also if checkbox is already in there it appends "0" to not have duplicates.

No matter what I tried so far, I can't get the uncheck part to trigger, tried many different ways. If there is any easy solution to this that i'm missing feel free to let me know

EDIT: My checkboxes are dynamically made by a user, so I think I can't simply include a onclick=stateChanged() function since it didn't work at all when i tried

Try to implements next way:

var IdOfLayers = [];
    var checkboxes = document.querySelectorAll("input[type='checkbox']");
    Array.from(checkboxes).map(function(checkbox){
        checkbox.addEventListener('change', function(e) {
            var name = e.target.name;
            
            if(e.target.checked) {
                IdOfLayers.push(e.target.name);
            } else {
                var idx = IdOfLayers.indexOf(name);
                if(idx !== -1) {
                    IdOfLayers.splice(idx, 1);
                }
            }
            console.log(IdOfLayers);
        });
    });

See my comments to your question. This, I believe, is all you need (run the code snippet below):

 const divElement = document.querySelector('#d'); /* A Set is the most efficient structure for adding and removing checkboxes You can always convert this to an array if that is ultimately what you need somewhere else. */ const IdOfLayers = new Set(); divElement.addEventListener('change', function(event) { const checkbox = event.target; const name = checkbox.name; if (checkbox.checked) { IdOfLayers.add(name); } else { IdOfLayers.delete(name); } // for debugging purposes or to convert to an array if that is what you need in the end const myArr = Array.from(IdOfLayers); console.log(myArr); });
 <div id="d"> <label>Checkbox 1 <input type="checkbox" name="c1" value="1"></label> <label>Checkbox 2 <input type="checkbox" name="c2" value="2"></label> <label>Checkbox 3 <input type="checkbox" name="c3" value="3"></label> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM