Skip to content
Related Articles
Open in App
Not now

Related Articles

How to enable or disable nested checkboxes in jQuery ?

Improve Article
Save Article
Like Article
  • Last Updated : 10 Dec, 2020
Improve Article
Save Article
Like Article

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.

Syntax:

// Select all child input of type checkbox
// with class child-checkbox
// And add the disabled attribute to them
$('.child-checkbox input[type=checkbox]')
    .attr('disabled', true);

After that, we add a click event listener to the parent checkbox, so when we click on the parent checkbox, if it is checked, all of its child checkboxes become enable. Else it’s all child checkboxes become disable.

Below is the implementation of this approach :

Example:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="utf-8">
  
    <title>
        How to enable or disable nested
        checkboxes in jQuery?
    </title>
  
    <!-- Link of JQuery cdn -->
    <script src=
    </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>
        // Select child-checkbox classes all checkbox 
        // And add disabled attributes to them
        $('.child-checkbox input[type=checkbox]').
            attr('disabled', true);
  
        // When we check parent-checkbox then remove disabled
        // Attributes to its child checkboxes
        $(document).on('click', 
            '.parent-checkbox input[type=checkbox]',
            function (event) {
  
                // If parent-checkbox is checked add 
                // disabled attributes to its child
                if ($(this).is(":checked")) {
                    $(this).closest(".container").
                        find(".child-checkbox > 
                        input[type=checkbox]").
                        attr("disabled", false);
                } else {
  
                    // Else add disabled attrubutes to its 
                    // all child checkboxes  
                    $(this).closest(".container").
                        find(".child-checkbox > 
                        input[type=checkbox]").
                        attr("disabled", true);
                }
            });
    </script>
</body>
  
</html>


Output:

When parent checkbox disable:

When parent checkbox enable:




My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!