I have a few checkboxes being created dynamically from a server-side callback function in google apps script. The checkboxes are created all with the same name "flavors". I can't seem to figure out how to addEventListener to each checkbox and have it function when the checkbox state is changed. If the checkbox is checked, i'd like to display some items, if it's not, i simply will hide the div for the display items.
How can i add the eventlisteners dynamically the same way i'm adding the checkboxes dynamically?
I've tried checkbox.addEventListener within the function that is creating the checkboxes dynamically, before and after appending the checkbox (see provided code). I've also tried making a function called addEventListeners(), which would just grab all elements by name using .getElementsByName(Name), then looping through each of the checkboxes and adding the event listener. Also tried changing it from "change" to "click" with no luck.
I always want the function displayFlavBlocks(chkboxID) to be run anytime any of the checkboxes are checked or unchecked (anytime the state of the checkbox changes).
html (heavily edited down):
<script>
google.script.run.withSuccessHandler(
function (flavors)
{
var div = document.getElementById("flavorOptions");
for (var i=0; i<flavors.length; i++)
{
var checkbox = document.createElement("input");
var chkboxValue = flavors[i];
var chkboxId = "f" + (i+1);
checkbox.type = "checkbox";
checkbox.name = "flavors";
checkbox.value = chkboxValue;
checkbox.id = chkboxId;
div.appendChild(checkbox);
// set each flavor checkbox to be checked by default
document.getElementById(chkboxId).checked = true;
}
addEventListeners();
}
).getBatchFlavs();
};
function addEventListeners() {
var checkboxes = document.getElementsByName("flavors");
for (var i=0;i<checkboxes.length;i++)
{
var chkboxId = checkboxes[i].id;
checkboxes[i].addEventListener("change", displayFlavBlocks(chkboxId));
}
}
function displayFlavBlocks(chkboxId) {
var checked = document.getElementById(chkboxId).checked;
if (checked)
{
if (chkboxId == "f1")
{
document.getElementById("f1block").style.display = "block";
// do some other stuff
}
}
}
</script>
The checkbox and label comes up perfectly on the dialog, and it is checked by default. But clicking and unclicking the checkbox does nothing. I checked by printing to console, and see that it prints that the state of the checkbox is true when the dialog first loads, then when i uncheck the checkbox, nothing is printed to the console and nothing happens (i've tested printing a couple things using innerHTML, and nothing gets printed when checking or unchecking).