[英]How to select all fields from a single box?
I have this sample: 我有这个样本:
CODE HTML: 代码HTML:
<div class="box1">
<fieldset>
<input type="checkbox" class="select-all">
<label>Select All </label>
</fieldset>
<fieldset>
<input type="checkbox">
<label>Checkbox1</label>
</fieldset>
<fieldset>
<input type="checkbox">
<label>Checkbox3 </label>
</fieldset>
<fieldset>
<input type="checkbox">
<label>Checkbox3 </label>
</fieldset>
</div>
<div class="box2">
<fieldset>
<input type="checkbox" class="select-all">
<label>Select All </label>
</fieldset>
<fieldset>
<input type="checkbox">
<label>Checkbox4 </label>
</fieldset>
<fieldset>
<input type="checkbox">
<label>Checkbox5 </label>
</fieldset>
<fieldset>
<input type="checkbox">
<label>Checkbox6 </label>
</fieldset>
</div>
CODE CSS: 代码CSS:
.box1{
background:#d9d9d9;
margin-bottom:20px;
}
.box2{
background:#ccc;
}
CODE JS: 代码JS:
$('.select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
}else{
$(':checkbox').each(function() {
this.checked = false;
});
}
});
What I want to do is that when the button "select-all" is checked, select all fields in a box. 我想做的是,当选中“全选”按钮时,选择一个框中的所有字段。
At this time, set all inputs ... and I wish only the current box. 此时,设置所有输入...,我只希望当前框。
How can I change my function so that it works? 如何更改我的功能使其起作用?
Thanks in advance! 提前致谢!
You can use .closest()
to find the parent div, then use .find()
method to get the checkboxes inside it, 您可以使用.closest()
查找父div,然后使用.find()
方法获取其中的复选框,
$('.select-all').click(function(event) {
if (this.checked) {
// Iterate each checkbox
$(this).closest("div").find(':checkbox').each(function() {
this.checked = true;
});
} else {
$(this).closest("div").find(':checkbox').each(function() {
this.checked = false;
});
}
});
You can reduce your code like this also, 您也可以像这样减少代码,
$('.select-all').click(function(event) {
var obj=this;
var parent = $(this).closest("div[class^=box]");
parent.find(':checkbox').each(function() {
this.checked = obj.checked;
});
});
As A.Wolf suggested, you can use like this too, 正如A.Wolf建议的那样,您也可以这样使用,
$('.select-all').change(function(event) {
$(this).closest('div[class^=box]').find(':checkbox').prop('checked', this.checked);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.