check child check box by parent check box in jquery

97 Views Asked by At

I am trying to check child check box by parent check box in Jquery. But code work properly for first time next its stop working

$(document).ready(function () {
    $("#append").delegate("#p0", "click", function () {
        if (this.checked == true) {
            $("#submenu0 input").attr('checked', true);
        } else {
            $("#submenu0 input").attr('checked', false);
        }
    });

HTML

<div id="append" name="append" style="background-color: white;">
    <input type="checkbox" id="p0" value="Administrative Boundary">
    <div id="submenu0" class="a" style=" margin-left: 29px ">
        <input type="checkbox" id="pc00" value="KBJNL:district_boundary_2011" checked="checked">District Boundary 2011
        <br>
    </div>
</div>
2

There are 2 best solutions below

0
On BEST ANSWER

You can use the checked status of the clicked checkbox, to update the other checkboxes.

See comments inline.

// Use change event, and on to bind events, delegate calls on inside
$("#append").on("change", "#p0", function() {
    $("#submenu0 :checkbox").prop('checked', $(this).is(':checked'));
    // if this checkbox is checked then check all the checkboxes inside #submenu0
});
0
On

use on in jquery for event delegation and also use prop() instead of attr()

$(document).ready(function () {
    $("#append").on("change","#p0", function() {
        $("#submenu0 input").prop('checked', this.checked);
    });
});

DEMO