I have nestable list with checkboxes and I need to work that check parent checkbox make all child checked and save children values into array.
I already figure out checking of all child checkboxes, when parent is checked? But I am not able to save their values at the same time.
HTML
<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>
JQuery
$('input:checkbox').change(function () {
var array=[];
if(type === "main-checkbox") {
var parent = $(this).closest('.dd-item');
if('$(parent).find('.sub-checkbox').is(":checked")) {
array.push($(parent).find('.sub-checkbox').prop('checked',this.checked).val());
}
}
});
This one return empty array and nothing is saved. Is possible to do it somehow like that?
Step6: while selecting the checkboxes and submitting the update button, function save() will be called, and the update process will be performed. Step7: Once the page gets refresh, the function load() will retain the checked checkboxes values.
In order to select all the checkboxes of a page, we need to create a selectAll () function through which we can select all the checkboxes together. In this section, not only we will learn to select all checkboxes, but we will also create another function that will deselect all the checked checkboxes.
With Pure JavaScript, the approach would be as follows:
toggleCheck()
. children
.children
variable whenever the main checkbox is click.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With