lundi 25 décembre 2017

Using jquery check/uncheck SelectAll checkbox when all the checkboxes in the group are checked/unchecked

I need SelectAll checkbox should be checked when all the li's in the group checkboxes are checked.

Here I am having two checkbox groups. I need optimized code. try to work two ID's combindly?

Note: If all li's are checked/unchecked other group should not be affected and vice-versa.

Please have a look at my work till now

    <ul>
            <li><input type="checkbox" id="one_select_all"/> Group ONE Selecct All</li>
            <li><input class="one_checkbox" type="checkbox" name="check[]"> This is Item 1</li>
            <li><input class="one_checkbox" type="checkbox" name="check[]"> This is Item 2</li>
            <li><input class="one_checkbox" type="checkbox" name="check[]"> This is Item 3</li>
            <li><input class="one_checkbox" type="checkbox" name="check[]"> This is Item 4</li>
            <li><input class="one_checkbox" type="checkbox" name="check[]"> This is Item 5</li>
            <li><input class="one_checkbox" type="checkbox" name="check[]"> This is Item 6</li>
    </ul>
    <ul>
            <li><input type="checkbox" id="two_select_all"/> Group TWO Selecct All</li>
            <li><input class="two_checkbox" type="checkbox" name="check[]"> This is Item 1</li>
            <li><input class="two_checkbox" type="checkbox" name="check[]"> This is Item 2</li>
            <li><input class="two_checkbox" type="checkbox" name="check[]"> This is Item 3</li>
            <li><input class="two_checkbox" type="checkbox" name="check[]"> This is Item 4</li>
            <li><input class="two_checkbox" type="checkbox" name="check[]"> This is Item 5</li>
            <li><input class="two_checkbox" type="checkbox" name="check[]"> This is Item 6</li>
   </ul>     


        <script>
        $("#one_select_all").change(function(){
            $(".one_checkbox").prop('checked', $(this).prop("checked"));
        });
        $("#two_select_all").change(function(){
            $(".two_checkbox").prop('checked', $(this).prop("checked")); 
        });
        $('.one_checkbox , .two_checkbox').change(function(){ 
            if(false == $(this).prop("checked")){ 
                $("#one_select_all").prop('checked', false);
            }else{
            $("#one_select_all").prop('checked', true);
            }
            if ($('.one_checkbox:checked, .two_checkbox:checked').length == $('.one_checkbox, .two_checkbox').length ){
                $("#one_select_all, #two_select_all").prop('checked', true);
            }else{
             $("#one_select_all, #two_select_all").prop('checked', false);
            }
        });
        </script>




Aucun commentaire:

Enregistrer un commentaire