实现多checkbox的互斥选中,看下图:AAA和BBB和CCC不能同时选中,也可以定义其他规则,CCC和EEE不能同时选中,DDD和EEE不能同时选中。
同时选中的时候要进行提示,那几个冲突了,并且将冲突去掉。
完整例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="/jquery/1.4.1/jquery.min.js"></script>
<script>
function clickCallBack(e){
var rule = [["0","1","4"],["2","4"],["3","4"]];
var ruleLabel = [["AAA","BBB","EEE"],["CCC","EEE"],["DDD","EEE"]];
if(!checkCan(rule,ruleLabel)){
e.checked =false;
}
}
function contains(obj,a) {
var i = a.length;
while (i--) {
if (a[i] == obj) {
return true;
}
}
return false;
}
function checkCan(rule,ruleLabel){
var checkedVals = new Array();
jQuery("input[name=test]:checked").each(function(){
checkedVals.push($(this).val());
});
jQuery.each(rule,function(index){
var ruleItem = $(this);
var flag =0;
for(i=0;i<ruleItem.length;i++){
if(contains(ruleItem[i], checkedVals)){
flag++;
}
}
if(flag>=ruleItem.length) {
var ruleLabelruleLabelItem = ruleLabel[index];
var promote = "";
var labelSize = ruleLabelItem.length;
for(i=0;i<labelSize;i++){
if(i < labelSize - 1){
promote += "'" + ruleLabelItem[i] + "'同";
} else {
promote += "'" + ruleLabelItem[i] + "'";
}
}
alert(promote+"是互斥的,不能同时选中!");
return false;
}
});
return true;
}
</script>
<title>Insert title here</title>
</head>
<body>
<input type="checkbox" name="test" value="0" onclick="clickCallBack(this)"/>AAA
<input type="checkbox" name="test" value="1" onclick="clickCallBack(this)"/>BBB
<input type="checkbox" name="test" value="2" onclick="clickCallBack(this)"/>CCC
<input type="checkbox" name="test" value="3" onclick="clickCallBack(this)"/>DDD
<input type="checkbox" name="test" value="4" onclick="clickCallBack(this)"/>EEE
<input type="checkbox" name="test" value="5" onclick="clickCallBack(this)"/>FFF
<input type="checkbox" name="test" value="6" onclick="clickCallBack(this)"/>GGG
<input type="checkbox" name="test" value="7" onclick="clickCallBack(this)"/>HHH
</body>
</html>