<HTML>
<HEAD>
<title>checkbox全選反選</title>
<script language="javascript">
//全選反選
function btnclick(id)
{
var cb=document.getElementById("list"+id).getElementsByTagName("input");
var as=document.getElementById("ckb"+id);
for(var i=0;i<cb.length;i++)
{
if(cb[i].type=="checkbox")
{
cb[i].checked=(as.checked==true)?true:false;
}
}
//alert(str)
}
//獲取選中項的值
function getall(id)
{
var str="";//不賦值的話會出現undefined
var cb=document.getElementById(id).getElementsByTagName("input");
for(var i=0;i<cb.length;i++)
{
if(cb[i].type=="checkbox")
{
if(cb[i].checked)
{
str+=cb[i].value+",";
}
}
}
alert(str);
}
//判斷父節點是否應該選中(只要子節點有選中的父節點必須選中)
function ckbparent(e,id)
{
if(e.checked)
{
document.getElementById("ckb"+id).checked=true;
}
else
{
var cb=document.getElementById("list"+id).getElementsByTagName("input");
var num=0;
for(var i=0;i<cb.length;i++)//迴圈判斷子節點是否有選擇項
{
if(cb[i].type=="checkbox")
{
if(cb[i].checked)
{
num++;
}
}
}
if(num>0)
{
document.getElementById("ckb"+id).checked=true;
}
else
{
document.getElementById("ckb"+id).checked=false;
}
}
}
</script>
<style>
.list1{ border:solid 1px #EAEAEA;}
.list1 li{ float:left; width:100px;}
</style>
</HEAD>
<body leftMargin="0" topMargin="0" >
<form name="Form1" method="post" id="Form1">
<div id="ckball">
<input type='checkbox' id='ckb1' value="01" onClick="btnclick('1')">all
<ul id="list1" class="list1">
<li><input type='checkbox' onClick="ckbparent(this,'1')" id="ck1" value="1">1</li>
<li><input type='checkbox' onClick="ckbparent(this,'1')" id="ck2" value="2">2</li>
<li><input type='checkbox' onClick="ckbparent(this,'1')" id="ck3" value="3">3</li>
<li><input type='checkbox' onClick="ckbparent(this,'1')" id="ck4" value="4">4</li>
</ul>
<input type='checkbox' id='ckb2' value="02" onClick="btnclick('2')">all
<ul id="list2" class="list1">
<li><input type='checkbox' onClick="ckbparent(this,'2')" id="ck5" value="5">5</li>
<li><input type='checkbox' onClick="ckbparent(this,'2')" id="ck6" value="6">6</li>
<li><input type='checkbox' onClick="ckbparent(this,'2')" id="ck7" value="7">7</li>
<li><input type='checkbox' onClick="ckbparent(this,'2')" id="ck8" value="8">8</li>
</ul>
</div>
<input type="button" id="baocun" value="取值" onClick="getall('ckball')">
</form>
</body>
</HTML>