Select all child checkboxes, checked them and save their value
With Pure JavaScript, the approach would be as follows:
- Use querySelector to retrieve the main check-box and add a click listener which runs a function say,
toggleCheck()
. - Use querySelectorAll to retrieve all the child check-boxes and assign them to a variable say,
children
. - You can then use the forEach() method to toggle each checkbox inside the
children
variable whenever the main checkbox is click. - Finally, add an
if statement
to the function that will push any child checkbox value to your array if it is checked and return it.
Check and run the following Code Snippet for a practical example of what I described above:
var main = document.querySelector(".main-checkbox");
var children = document.querySelectorAll(".sub-checkbox");
function toggleCheck() {
var array=[];
children.forEach(child => {
child.checked = child.checked == true ? false : true
if (child.checked == true) {
array.push(child.value);
}
})
console.log(array);
return array;
}
main.addEventListener("click", toggleCheck);
<ul>
<li class="main-parent">
<input class="main-checkbox" type="checkbox" value="id">
<ul>
<li><input class="sub-checkbox" type="checkbox" value="1"></li>
<li><input class="sub-checkbox" type="checkbox" value="2"></li>
<li><input class="sub-checkbox" type="checkbox" value="3"></li>
</ul>
</li>
</ul>