2015-10-31 81 views
0

我有一組複選框,它們具有data-groupiddata-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 

    } 
    }  
}); 
+2

你爲什麼不使用無線電盒代替 –

回答

5

既然你想允許從一個組中選擇一個項目,單選按鈕將是一個更好的選擇。

但是,如果你仍然想使用複選框,然後你可以使用過濾屬性選擇像

$('.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" />

+0

http://jsfiddle.net/arunpjohny/qzv801qv/ –

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

試試這個

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>