0

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

     }
   }    
 });
1
  • 2
    Why don't you use radio box instead Commented Oct 31, 2015 at 8:54

2 Answers 2

5

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" />

Sign up to request clarification or add additional context in comments.

Comments

3
var group1 = '1'
$('body').find("[data-groupid='" + group1 + "']").prop('checked',true);

try this

demo

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.