Reputation: 7778
I have a set of checkboxes that have a data-groupid
and data-multichoice
attributes.
group 1 : data-groupid= "1" data=multichoice="0"
(10 boxes)
group 2 : data-groupid= "2" data=multichoice="0"
(10 boxes)
How to I disable all boxes on one group at once?
//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
}
}
});
Upvotes: 0
Views: 1443
Reputation: 15555
var group1 = '1'
$('body').find("[data-groupid='" + group1 + "']").prop('checked',true);
try this
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>
Upvotes: 3
Reputation: 388316
Since you want to allow to select only 1 item from a group, radio buttons will be a better choice.
But if you still want to use checkbox, then you can filter using attribute selector like
$('.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" />
Upvotes: 5