这是我的HTML代码
<div class="panel-body">
<p> <input name="select_all" type="checkbox" value="1"> Select/Deselect All</p>
<div class="input-group"><span class="input-group-addon">
<span><input checked="checked" name="manage_group" type="checkbox" value="1"></span>
<span class="form-control">Create/manage groups of candidates</span
</div>
<div class="input-group"><span class="input-group-addon">
<span><input checked="checked" name="manage_candidate" type="checkbox" value="1"></span>
<span class="form-control">Modify candidate details</span>
</div>
</div>
如果&#39; select_all&#39;我想检查所有复选框(仅在父div中)如果选中&#39; select_all&#39;选中复选框并取消选中全部。未经检查。
这是我的jquery代码:
$(".panel-body p input[type='checkbox']").click(function() {
if(this.checked){
//alert('Checked');
var selected = this.closest(".panel-body");
$(selected+"div input[type='checkbox']").each(function () {
alert ('Hi');
});
}else{
}
});
但它不起作用。它不接受选择&#39;选择器内的变量。如何选择所选元素中的所有复选框?
答案 0 :(得分:4)
你的问题是这一行: -
this.closest(".panel-body");
其中this
是元素,而不是jQuery对象。
你可以达到你想要的效果: -
$(".panel-body p input[type='checkbox']").change(function() {
var selected = $(this).closest(".panel-body");
selected.find("div input[type='checkbox']").prop('checked', this.checked);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body">
<p>
<input name="select_all" type="checkbox" value="1">Select/Deselect All</p>
<div class="input-group"><span class="input-group-addon">
<input checked="checked" name="manage_group" type="checkbox" value="1"></span>
<span class="form-control">Create/manage groups of candidates</span>
</div>
<div class="input-group"><span class="input-group-addon">
<input checked="checked" name="manage_candidate" type="checkbox" value="1"></span>
<span class="form-control">Modify candidate details</span>
</div>
</div>
&#13;
答案 1 :(得分:1)
你可以这样做。查找距离最近checkbox
的所有.panel-body
,并根据checked
状态更改select_all
媒体资源。
$(":checkbox[name=select_all]").change(function () {
$(this).closest('.panel-body').find(':checkbox').not(this).prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body">
<p> <input name="select_all" type="checkbox" value="1"> Select/Deselect All</p>
<div class="input-group">
<span class="input-group-addon">
<input checked="checked" name="manage_group" type="checkbox" value="1">
</span>
<span class="form-control">Create/manage groups of candidates</span>
</div>
<div class="input-group">
<span class="input-group-addon">
<input checked="checked" name="manage_candidate" type="checkbox" value="1">
</span>
<span class="form-control">Modify candidate details</span>
</div>
</div>