How to enable or disable nested checkboxes in jQuery ?

In this article, we will see how to enable or disable nested checkboxes in jQuery. To do that, we select all child checkboxes and add disabled attributes to them with the help of the attr() method in jQuery so that all checkboxes will be disabled.

1. Syntax:

$('.child-checkbox input[type=checkbox]')
    .attr('disabled', true);

2. Example:

Run the program to get the result:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>
        How to enable or disable nested
        checkboxes in jQuery?
    </title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
    </script>
</head>
<body>
    <div class="container">
        <div class="parent-checkbox">
            <input type="checkbox"> Govt. employe
        </div>
        <div class="child-checkbox">
            <input type="checkbox"> ldc
            <input type="checkbox"> clerk
            <input type="checkbox"> watchmen
        </div>
    </div>
    <script>
        $('.child-checkbox input[type=checkbox]').attr('disabled', true);
        $(document).on('click', '.parent-checkbox input[type=checkbox]',
            function (event) {
                if ($(this).is(":checked")) {
                    $(this).closest(".container").
                        find(".child-checkbox > input[type=checkbox]").attr("disabled", false);
                } else {
                    $(this).closest(".container").
                        find(".child-checkbox > input[type=checkbox]").attr("disabled", true);
                }
            });
    </script>
</body>
</html>