当前位置: 动力学知识库 > 问答 > 编程问答 >

check all the checkboxes by clicking on the "ALL" checkbox using 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)

}

});

});

网友答案:

You haven't mentioned your issue in the question. Assuming you want to check all the checkboxes with class name child when clicking on checkbox chkMain

$(function(){
    $("#chk_all").click(function(){
        $("input:checkbox").attr("disabled", !(this.checked));
    });
});

Also you are having an invalid HTML. More than one element is having the same id.

网友答案:

Your question is very unclear. There is already an answer provided to enable/disable your checkboxes. However, based upon what I could gather from your code, it seems like you are wanting to create an all check/uncheck checkbox?

If so, you could do the following as a simple 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 />

Your checkboxes probably should contain a name. Also, using the same ID on multiple DOM elements is not allowed and will cause errors.

分享给朋友:
您可能感兴趣的文章:
随机阅读: