mercredi 23 septembre 2015

How to check a checkbox when all the checkboxes below it are checked?

I am dynamically adding tr and td to a table this way.

var arr=[1,2,3];

                var trtest = "<tr>";
                trtest = trtest +"<tr><td><input type='checkbox' onclick=onAllCheckBoxClick('" + arr+ "') class = 'all' id ='all'>All</td></tr>";

$.each(arr, function(i, tmp) {
                    trtest = trtest +"<tr><td><input type='checkbox' onclick=onCheckBoxClick('" + this+ "','" + arr+ "') class = 'all' id ='"+tmp+"'/>"+tmp+"</td></tr>";
                });

This code is working And i am getting 4 checkboxes this way,

All
    1

    2

    3

Here, when i try to check individual child checkbox's 1,2,3 then All checkbox have to be selected.

I tried adding this click event to each checkbox this way,

function onCheckBoxClick(checkBoxId,arr){
        var chkselected = [];
            $('#generateTable').find(':checkbox:checked').each(function() {
                chkselected.push(this.id);
            });
            //
            if (arr.split(",").length == chkselected.length && ($('#'+checkBoxId).is(':checked') == true)) {
                $('#all').attr('checked',true);
            }
            //
            else if (arr.split(",").length == chkselected.length && ($('#'+checkBoxId).is(':checked') == false)) { 
                $('#all').attr('checked',false);                
            }
}

Issue is when i check 1,2, and lastly 3 immediately All check box is getting checked,

But when I try to check 3,2 and then 1 finally , All check box is not checked.

I want All to be checked if 1,2,3 are checked and All to be unchecked if any of 1,2,3 is unchecked.

I am new to jquery and so can anyone help me in this issue?

Thanks




Aucun commentaire:

Enregistrer un commentaire