The following javascript works but not in my application as a product filter. In my case, clicking the checkbox displays the div but unchecking does not hide the div. Applying, onclick event to the checkbox is also not doable. Is it possible to have two addEventlistener ‘click’ events, one for opening and one for closing?
const check = document.getElementById("checkbox-id");
if (check) {
check.addEventListener('click', event => {
this.event = event;
if (check.checked) {
document.getElementById("showDiv").style.display = "block";
} else {
document.getElementById("showDiv").style.display = "none";
}
});
}
#showDiv {
display: none;
width: 100%;
background-color: #252525;
color: #ffffff;
}
<form>
<input class="input" type="checkbox" id="checkbox-id">
</form>
<div id="showDiv">Show / hide</div>
I have tried the following (and others) but I have not been able to hide the box after being revealed. Just know, the click event is the only way that has produced a result. Happy to provide any other info if needed. TY
const general = document.getElementById("checkbox-id");
const checkOpen = () => {
document.getElementById("showDiv").style.display = "block";
}
const checkClosed = () => {
document.getElementById("showDiv").style.display = "none";
}
if (element) {
element.addEventListener('click', event => {
this.event = event;
checkOpen();
checkClosed();
});
}
2
Answers
Here’s the corrected solution to make your code work as expected. The issue in your code lies in trying to invoke both checkOpen and checkClosed on the same event without conditionally executing one based on the checkbox state.
Use the following code to correctly toggle the visibility of the div:
Solution:
Why This Works:
The single addEventListener(‘click’) handles both showing and hiding the div by checking the state of the checkbox (checked property).
This approach is simple, avoids redundancy, and works in any JavaScript environment.
Coding
doesn’t make sens, because this is a form’s element, not a booolean value.
a way to code this… (with some improvements).