vendredi 23 septembre 2022

How to get value of checked children checkboxes from checked parent checkboxes in javascript

I have a list of dynamic checkboxes(parent checkboxes) that also have children checkboxes, i want to get only the selected children checkboxes of the selected parent checkboxes.

This is what i have tried:

i used document.querySelectorAll() to get all the checked parent checkboxes, i iterated through each of them using foreach loop, but for whatever reason, i can't seem to get array list of all the checked children checkboxes so i can iterate through them and get their values... this where am stuck. below is the code of what i have done

var test_names= document.querySelectorAll("input[class='g-t-l-p']:checked");

        test_names.forEach(function(test_name) {
            var testname = test_name.innerHTML;
            var parentdiv = test_name.parentElement.parentElement.parentElement;
            if(parentdiv != null || parentdiv != undefined) {
                console.log('parentdiv',parentdiv)
            var childtestbutton = parentdiv.lastElementChild;
            
                if(childtestbutton != null || childtestbutton != undefined) {
                    var childtestprof = parentdiv.lastElementChild.previousElementSibling.lastElementChild.lastElementChild.value;
                    var childtestchecked = parentdiv.lastElementChild.previousElementSibling.firstElementChild.firstElementChild;
                    
                    if(childtestchecked != null || childtestchecked != undefined) {
                        console.log(childtestchecked)
                        console.log(childtestchecked.checked)
                        if(childtestchecked.checked == true && childtestchecked.checked != null || childtestchecked.checked != undefined) {
                            console.log('lengtha',childtestchecked.nextElementSibling.innerHTML)
                            var nnc = document.querySelectorAll("input[class='c-g-t-l-p']:checked");
                            console.log('nnc',nnc)
                            // var array = []
                            // for (var i = 0; i < childtestchecked.length; i++) {
                            //   array.push(checkboxes[i].value)
                            // }
                            // console.log('button',childtestprof)
                            // console.log('childtestnames',childtestnames)   
                            
                        }
                    }else {
                        console.log('box not checked');
                    }
                    
                }
            }else {
                console.log('no parent div')
            }
        });

Below is an illustration and snippet; loop through checkboxes javascript

Thank you in anticipation of your response




Aucun commentaire:

Enregistrer un commentaire