mardi 26 juillet 2016

Child Checkboxes running code when Parent Checkbox is unchecked

I've got a set of parent checkboxes and children checkboxes, and each checkbox (parent or child), runs a piece of code. When I check the parent checkbox, the parent checkbox runs it's code, and the child checkbox doesn't. However, when I uncheck the parent checkbox, the child checkbox runs its code. Here's an example code:

HTML Code:
 <li>
        <input type="checkbox" onclick="validate()"  name="Parent" id="Parent">
        <label for="Parent">Parent</label>
        <ul>
            <li>
                <input type="checkbox" onclick="validate()"  name="Child" id="Child">
                <label for="Child">Child</label>
            </li>
 </ul>

 JavaScript code:
 $(function () {

$('input[type="checkbox"]').change(function (e) {
    var checked = $(this).prop("checked"),
        container = $(this).parent(),
        siblings = container.siblings();

    container.find('input[type="checkbox"]').prop({
        indeterminate: false,
        checked: checked
    });

    function checkSiblings(el) {
        var parent = el.parent().parent(),
            all = true;

        el.siblings().each(function () {
            return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked);
        });

        if (all && checked) {
            parent.children('input[type="checkbox"]').prop({
                indeterminate: false,
                checked: checked
            });
            checkSiblings(parent);
        } else if (all && !checked) {
            parent.children('input[type="checkbox"]').prop("checked", checked);
            parent.children('input[type="checkbox"]').prop("indeterminate", (parent.find('input[type="checkbox"]:checked').length > 0));
            checkSiblings(parent);
        } else {
            el.parents("li").children('input[type="checkbox"]').prop({
                indeterminate: true,
                checked: false
            });
        }
    }

    checkSiblings(container);
});
});

  var validate=function(){
    if(document.getElementById("Parent").checked){alert("Parent!");}   
    if(document.getElementById("Child").checked){alert("Child!");}   }




Aucun commentaire:

Enregistrer un commentaire