【发布时间】:2017-11-19 17:45:19
【问题描述】:
我正在尝试将一些 jQuery 应用于复选框,但仅限于最近的 div。
我有一个 x 动态创建的复选框列表 - 如果所有复选框都是空白的,那么我希望它们都显示为已选中。
HTML
<div class="col-lg-6">
<label class="checkbox-inline"><input type="checkbox" name="permissions[]" class="perm limitall" value="1">1</label>
<label class="checkbox-inline"><input type="checkbox" name="permissions[]" class="perm limitall" value="2">2</label>
<label class="checkbox-inline"><input type="checkbox" name="permissions[]" class="perm limitall" value="3">3</label>
</div>
$(document).ready(function () {
if ($('.limitall:checkbox:checked').length == 0){
$('.limitall').prop('checked', true);
}
$(".limitall").change(function(){
if ($('.limitall:checkbox:checked').length == 0){
$('.limitall').prop('checked', true);
}
});
});
只要页面上只有一组具有 limitall 类的“一组”项目,它就可以正常工作 - 如果有更多,那么这会将两个组视为一组,并且只有在所有 10 个都是空白的情况下才有效。
如果我有:
<div class="col-lg-6">
<label class="checkbox-inline"><input type="checkbox" name="permissions[]" class="perm limitall" value="1">1</label>
<label class="checkbox-inline"><input type="checkbox" name="permissions[]" class="perm limitall" value="2">2</label>
<label class="checkbox-inline"><input type="checkbox" name="permissions[]" class="perm limitall" value="3">3</label>
</div>
<div class="col-lg-6">
<label class="checkbox-inline"><input type="checkbox" name="permissions2[]" class="perm2 limitall" value="1">1</label>
<label class="checkbox-inline"><input type="checkbox" name="permissions2[]" class="perm2 limitall" value="2">2</label>
<label class="checkbox-inline"><input type="checkbox" name="permissions2[]" class="perm2 limitall" value="3">3</label>
</div>
这将其视为一组 6 而不是 2 组 3 - 我如何确保不会发生这种情况并且每组都被独立处理?
上面的 HTML 结构将始终适用,因此复选框始终位于一个标签内,该标签位于一个带有 col-lg-6 类的 div 内,但输入的名称是动态设置的,所以我不能使用它
【问题讨论】:
标签: jquery checkbox jquery-selectors