我有一组具有data-groupid
和data-multichoice
属性的复选框。
第1组:data-groupid= "1" data=multichoice="0"
(10盒)
第2组:data-groupid= "2" data=multichoice="0"
(10盒)
如何一次禁用一个组中的所有框?
//function will catch any click on any checkbox with class=lvl
$('.lvl').click(function () {
//check if box was checked
if ($(this).is(":checked")) {
//check if data-attribute is NOT a multi-choice
if (!($(this).data("multichoice"))) {
//disable all checkboxes that have the same group-id
$(this).data("groupid") ... HELP HERE
}
}
});
答案 0 :(得分:5)
由于您希望仅允许从组中选择1个项目,因此单选按钮将是更好的选择。
但如果您仍想使用复选框,则可以使用
等属性选择器进行过滤
$('.lvl').click(function() {
//check if box was checked
if (this.checked) {
//check if data-attribute is NOT a multi-choice
if (!$(this).data("multichoice")) {
$('.lvl[data-groupid="' + $(this).data('groupid') + '"]').not(this).prop('checked', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="lvl" type="checkbox" data-groupid="1" data-multichoice="0" />
<input class="lvl" type="checkbox" data-groupid="1" data-multichoice="0" />
<input class="lvl" type="checkbox" data-groupid="1" data-multichoice="0" />
<br />
<input class="lvl" type="checkbox" data-groupid="2" data-multichoice="0" />
<input class="lvl" type="checkbox" data-groupid="2" data-multichoice="0" />
<input class="lvl" type="checkbox" data-groupid="2" data-multichoice="0" />
<input class="lvl" type="checkbox" data-groupid="2" data-multichoice="0" />
答案 1 :(得分:3)
var group1 = '1'
$('body').find("[data-groupid='" + group1 + "']").prop('checked',true);
试试这个
var group1 = '1'
$('body').find("[data-groupid='" + group1 + "']").prop('checked',true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="vehicle" data-groupid="1">I have a bike
<br>
<input type="checkbox" name="vehicle" data-groupid="2" >I have a car
<br>
<input type="checkbox" name="vehicle" data-groupid="1">I have a bike
<br>
<input type="checkbox" name="vehicle" data-groupid="2" >I have a car
<br>
<input type="checkbox" name="vehicle" data-groupid="1">I have a bike
<br>
<input type="checkbox" name="vehicle" data-groupid="2" >I have a car
<br>