Ideally when whichever group's checkbox is checked, divs are created repping the animals of that group and when unchecking whichever group, the divs of that group are removed. My problem is whenever I uncheck one group, it removes the divs from all groups along with the container, and prevents the method for creating divs from working again if rechecked. Why is this and how do I fix it? Thanks.
var cont = document.getElementById('cont');
function test(x) {
var selected = x.checked;
if (selected == true) {
array.forEach(function(element) {
if (element.sort == x.id) {
var div = document.createElement('div');
div.id = x.id;
var header = document.createElement('h4');
header.innerHTML = element.title;
div.appendChild(header);
cont.appendChild(div);
}
})
}
if (selected == false) {
var zed = cont.querySelectorAll(x.id);
cont.remove(zed);
}
}
var array = [
{title: 'Shark', sort: 'Sea'},
{title: 'Whale', sort: 'Sea'},
{title: 'Tuna', sort: 'Sea'},
{title: 'Cow', sort: 'Farm'},
{title: 'Sheep', sort: 'Farm'},
{title: 'Chicken', sort: 'Farm'},
]
.results-container {
display: flex;
flex-direction: column;
width: 200px;
height: auto;
min-height: 50px;
margin-top: 10px;
background-color:lightskyblue;
padding: 10px;
}
.results-container div {
display: flex;
background-color: white;
height: 40px;
width: 100%;
border: 1px solid black;
margin-bottom: 2px;
justify-content: center;
font-size: 10px;
}
<div class='filter-container'>
Sea: <input type="checkbox" id = 'Sea' onClick="test(this)" />
Farm: <input type="checkbox" id="Farm" onClick="test(this)"/>
</div>
<div id='cont' class='results-container'></div>
Aucun commentaire:
Enregistrer un commentaire