Como criar varios checkbox com suboption com o id diferente e conseguir selecionar eles no javascript
12/01/2022
0
<div class="container">
<ul>
<li>
<input type="checkbox" id="option"><label for="option"> Electronics</label>
<ul>
<li><label><input type="checkbox" class="subOption"> Laptops</label></li>
<li><label><input type="checkbox" class="subOption"> TVs</label></li>
<li><label><input type="checkbox" class="subOption"> Microphones</label></li>
</ul>
</li>
<li>
<input type="checkbox" id="zoption"><label for="zoption"> baba</label>
<ul>
<li><label><input type="checkbox" class="subOption2"> TVs</label></li>
<li><label><input type="checkbox" class="subOption2"> popo</label></li>
</ul>
</li>
</ul>
</div>
<script >
var checkboxes = document.querySelectorAll('input.subOption'),
checkall = document.getElementById('option');
for(var i=0; i<checkboxes.length; i++) {
checkboxes[i].onclick = function() {
var checkedCount = document.querySelectorAll('input.subOption:checked').length;
checkall.checked = checkedCount > 0;
checkall.indeterminate = checkedCount > 0 && checkedCount < checkboxes.length;
}
}
checkall.onclick = function() {
for(var i=0; i<checkboxes.length; i++) {
checkboxes[i].checked = this.checked;
}
}
</script>
<ul>
<li>
<input type="checkbox" id="option"><label for="option"> Electronics</label>
<ul>
<li><label><input type="checkbox" class="subOption"> Laptops</label></li>
<li><label><input type="checkbox" class="subOption"> TVs</label></li>
<li><label><input type="checkbox" class="subOption"> Microphones</label></li>
</ul>
</li>
<li>
<input type="checkbox" id="zoption"><label for="zoption"> baba</label>
<ul>
<li><label><input type="checkbox" class="subOption2"> TVs</label></li>
<li><label><input type="checkbox" class="subOption2"> popo</label></li>
</ul>
</li>
</ul>
</div>
<script >
var checkboxes = document.querySelectorAll('input.subOption'),
checkall = document.getElementById('option');
for(var i=0; i<checkboxes.length; i++) {
checkboxes[i].onclick = function() {
var checkedCount = document.querySelectorAll('input.subOption:checked').length;
checkall.checked = checkedCount > 0;
checkall.indeterminate = checkedCount > 0 && checkedCount < checkboxes.length;
}
}
checkall.onclick = function() {
for(var i=0; i<checkboxes.length; i++) {
checkboxes[i].checked = this.checked;
}
}
</script>
Angelica Cardoso
Curtir tópico
+ 0
Responder
Clique aqui para fazer login e interagir na Comunidade :)