通过使用jquery单击“ALL”复选框来检查所有复选框

时间:2011-01-11 17:02:52

标签: jquery

<body>                                           
<input type="checkbox" id="chkMain" />
<input type="checkbox" id="chkMain1" />
<input type="checkbox" id="chkMain2" />

<br>
<P><input class="child" type="checkbox" id="chk1" disabled="true" />
<input class="child" type="checkbox" id="chk" disabled="true" />
<input class="child" type="checkbox" id="chk" disabled="true" />
<input class="child" type="checkbox" id="chk" disabled="true" />
<input class="child" type="checkbox" id="chk" disabled="true" />
<input class="child" type="checkbox" id="chk" disabled="true" />
<input class="child" type="checkbox" id="chk_all" disabled="true" />ALL</p></br>


$(function(){           
    $("input[id^=chkMain]").click(function(){               
        var otherCks = $("input[id^=chkMain]").not(this);
        if( !$(this).is( ":checked" )) {                        
            $(".child").attr("disabled" , true );                                     
            otherCks.removeAttr ( "disabled" );
        }                   
        else {                        
            $(".child").removeAttr ( "disabled" );                  
            otherCks.attr("disabled" , true)
        }          
    });      
 });

2 个答案:

答案 0 :(得分:2)

您在问题中没有提到您的问题。假设您在单击复选框chkMain

时要检查所有带有类名子的复选框
$(function(){
    $("#chk_all").click(function(){
        $("input:checkbox").attr("disabled", !(this.checked));
    });
});

您的HTML也是无效的。多个元素具有相同的ID。

答案 1 :(得分:0)

你的问题很不清楚。 已经有一个答案可以启用/禁用您的复选框。但是,根据我从代码中收集的内容,您似乎想要创建一个全部选中/取消选中复选框?

如果是这样,您可以执行以下操作作为简单的check-all / uncheck-all:

<script type="text/javascript">
$(document).ready(function() {
    $('input.check_all').click(function() {
        if ($(this).attr('checked'))
        {
            $('input.child, input.check_all').attr('checked', 'checked');
        }
        else
        {
            $('input.child, input.check_all').removeAttr('checked');
        }
    });
});
</script>

<input class="check_all" type="checkbox" name="foo[]" /> All<br />
<input class="child" type="checkbox" name="foo[]" /><br />
<input class="child" type="checkbox" name="foo[]" /><br />
<input class="child" type="checkbox" name="foo[]" /><br />
<input class="child" type="checkbox" name="foo[]" /><br />
<input class="child" type="checkbox" name="foo[]" /><br />
<input class="child" type="checkbox" name="foo[]" /><br />
<input class="child" type="checkbox" name="foo[]" /><br />
<input class="child" type="checkbox" name="foo[]" /><br />
<input class="child" type="checkbox" name="foo[]" /><br />
<input class="child" type="checkbox" name="foo[]" /><br />

您的复选框可能应包含名称。此外,不允许在多个DOM元素上使用相同的ID,这将导致错误。

相关问题