Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

javascript - Check all other checkboxes when one is checked

I have a form and group of checkboxes in it. (These checkboxes are dynamically created but I dont think it is important for this question). The code that generates them looks like this (part of the form):

<div id="ScrollCB">
    <input type="checkbox" name="ALL" value="checked" checked="checked">
    All (if nothing selected, this is default) <br>
    <c:forEach items="${serviceList}" var="service">
       <input type="checkbox" name="${service}" value="checked"> ${service} <br>
    </c:forEach>
</div>

What I want to do is control, whether the checkbox labeled "ALL" is checked and if yes - check all other checkboxes (and when unchecked, uncheck them all).

I tried doing this with javascript like this (found some tutorial), but it doesnt work (and Im real newbie in javascript, no wonder):

<script type="text/javascript">
  $ui.find('#ScrollCB').find('label[for="ALL"]').prev().bind('click',function(){
  $(this).parent().siblings().find(':checkbox').attr('checked',this.checked).attr('disabled',this.checked);
}); });
</script>

Could you tell me some simple approach how to get it work? Thanks a lot!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

demo

updated_demo

HTML:

<label><input type="checkbox" name="sample" class="selectall"/> Select all</label>

<div id="checkboxlist">

    <label><input type="checkbox" name="sample[]"/>checkbox1</label><br />
    <label><input type="checkbox" name="sample[]"/>checkbox2</label><br />
    <label><input type="checkbox" name="sample[]"/>checkbox3</label><br />
    <label><input type="checkbox" name="sample[]"/>checkbox4</label><br />

</div>

JS:

$('.selectall').click(function() {
    if ($(this).is(':checked')) {
        $('div input').attr('checked', true);
    } else {
        $('div input').attr('checked', false);
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...