I have a sequence of divs with some similar data-attributes. I would like that when the user selects the checkbox, the divs corresponding to it appear when checked.
The code works to show divs, but when the checkbox is not selected, divs keep showing up.
.letters{
display: none;
}
B
B
B
A
B
C
A
C
A
a
b
c
const elements = document.querySelectorAll(".letters")
const inputs = document.querySelectorAll("input")
inputs.forEach(item => {
item.addEventListener('change', () => {
if (item.checked){
elements.forEach(e => {
if (e.getAttribute('data-text') == item.value) {
e.style.display = "block";
}else{
e.style.display = "none";
}
})
}
})
})
How to make the divs hide when unchecked and keep the other showing when checked?
Answer
Please add an else block to hide element when the checkbox is uncheck.
const elements = document.querySelectorAll(".letters");
const inputs = document.querySelectorAll("input");
inputs.forEach(item => {
item.addEventListener('change', function() {
if (this.checked) {
elements.forEach(e => {
if (e.getAttribute('data-text') == this.value) {
e.style.display = "block";
}
})
} else {
elements.forEach(e => {
if (e.getAttribute('data-text') == this.value) {
e.style.display = "none";
}
})
}
})
});
.letters {
display: none;
}
B
B
B
A
B
C
A
C
A
a
b
c
No comments:
Post a Comment