2015-10-31 33 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>