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
name="x" id="x"(for example) specified. But I don't even understand why that is so. If you take theelsebranch to theif (checked)test, why would you be testing now for false using the id of the element? This seems an unnecessary redundant check. And ifIdOfLayershold checked checkboxes (you remove their names from this when they are unchecked), what is the point of adding a '0' when they are checked? You cannot doubly check a check a checkbox. You add the name when a box is checked; you remove it when it is unchecked. (more..)eventas the argument to your event handler.