如何启用或禁用jQuery中的嵌套复选框

如何启用或禁用jQuery中的嵌套复选框

在这篇文章中,我们将看到如何启用或禁用jQuery中的嵌套复选框。要做到这一点,我们选择所有的子复选框,并在jQuery的attr()方法的帮助下给它们添加禁用属性,这样所有的复选框都会被禁用。

语法:

// 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);

之后,我们给父复选框添加一个点击事件监听器,所以当我们点击父复选框时,如果它被选中,它的所有子复选框都会变成启用状态。否则,它的所有子复选框都变成禁用状态。

下面是这种方法的实施。

示例:

<!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=
"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>
        // 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>

输出:

当父级复选框禁用时。

如何启用或禁用jQuery中的嵌套复选框?

当父级复选框启用时。

如何启用或禁用jQuery中的嵌套复选框?
如何启用或禁用jQuery中的嵌套复选框?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程