问题
I am trying to do group checkboxes by selecting selectAll. Please check JSFiddle for code sample
JSFiddle
<fieldset>
<!-- these will be affected by check all -->
<div><input type="checkbox" ID="checkall1" onclick="CheckAllClick('checkall1');"> Check all</div>
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
</fieldset>
<fieldset>
<!-- these won't be affected by check all; different field set -->
<div><input type="checkbox" ID="checkall2" onclick="CheckAllClick('checkall2');"> Check all</div>
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
<div><input type="checkbox"> Checkbox</div>
</fieldset>
function CheckAllClick(id){
alert(id);
$(id).closest('fieldset').find(':checkbox').prop('checked', this.checked);
}
Part 2: Continue
回答1:
You have some issues in your function: Try this way:
Js
function CheckAllClick(elem) {
$(elem).closest('fieldset').find(':checkbox').prop('checked', elem.checked);
}
Markup
<input type="checkbox" ID="checkall1" onclick="CheckAllClick(this);">Check all</div>
Fiddle
Pass the element in the onclick function as this
and access it in your code.
If you can go with jquery approach then:
Add a class to your checkall check boxes
<input type="checkbox" class="checkAll" ID="checkall1" >Check all
With the same code, if you want to make the label click to check the checkbox then just wrap them in label
tag, same thing you can do with all the checkboxes by wrapping them in label which generally is a standard way:
<label><input type="checkbox" class="checkAll" ID="checkall1" >Check all<label>
Bind an event handler to a class
$('.checkAll').on('change', function(){
$(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
})
Fiddle
回答2:
function CheckAllClick(id){
alert(id);
$(id).closest('fieldset').find(':checkbox').prop('checked', 'checked');
}
The simplest solution is just to changed the checked property to checked seeing as you only selecting inputs you want already
And pass this into your onclick
<div><input type="checkbox" ID="checkall2" onclick="CheckAllClick(this);"> Check all</div>
回答3:
What you probably want is this.
$('[id^=checkall]').click(function(){
$(this).closest('fieldset').find(':checkbox').not(this).prop('checked', function(i,oldval){
return !oldval;
});
});
Fiddle
来源:https://stackoverflow.com/questions/17538488/group-checkboxes-in-jsfiddle-part-1