I was trying to create a chip when a checkbox is checked by adding an eventlistener function to the checkbox but it is not happening . I think the element is not being inserted to the html .
Here is the code
let ChoosenFiltercontainer = document.getElementById('ChoosenFiltercontainer')
let FilterDropdownsElems = document.querySelector('.FilterDropdowns');
let FilterDropdownsElem = FilterDropdownsElems.querySelectorAll('[type=checkbox]');
let customid = "";
for (let i = 0; i < FilterDropdownsElem.length; i++) {
customid = customid + FilterDropdownsElem[i].id + i;
FilterDropdownsElem[i].addEventListener('click', function(customid) {
ChoosenFiltercontainer.innerHTML += `<div class="col-md-auto " id=${customid} style="display:none;" >
<div class="chip chip-outline btn-outline-dark rounded-pill" data-mdb-ripple-color="dark">
${FilterDropdownsElem[i].id} <i class="close fas fa-times" style="font-size: small;"></i>
</div>
</div>`;
if (FilterDropdownsElem[i].checked == true) {
document.getElementById('customid').style.display = "block";
} else {
document.getElementById('customid').style.display = "none";
}
}.bind(this, customid))
}
I think that i am not using the innerHTML property correctly
3
Answers
I am not sure about the rest of your code since you haven’t provided the html and CSS files.
Anyways reading your code, and using customId as a string rather than as a variable could be the problem, if everything else is fine.
try changing this to
do the same for the display = "none" case
It looks like there might be an issue with how you’re trying to set the display property based on the checkbox state. Also, there is an issue with the way you’re trying to set the ID of the dynamically created div.
Try this:
Use
event.target
to get the clicked checkbox element inside the event handler.Remove the unnecessary check for checkbox state
(if (FilterDropdownsElem[i].checked == true))
because it’s redundant.Use
div.remove()
to remove the dynamically created div when the corresponding checkbox is unchecked.I always suggest delegation so I will refactor instead of debugging your code which has some strange statements, like your .bind
Here is a version that delegates from the filterDropdown container and the ChoosenFiltercontainer
I added the checkbox ID to the close as a data attribute so we can uncheck the filter if we close it