Javascript全选,反选,全不选
2009-02-09 19:59 daixueji 阅读(7692) 评论(7) 编辑 收藏 举报
闲来无事,发布一个javacript写的全选,反选,全不选功能的代码:
Code
<html>
<head>
<script type="text/javascript">
function checkEvent(name,allCheckId)
{
var allCk=document.getElementById(allCheckId);
if(allCk.checked==true)
checkAll(name);
else
checkAllNo(name);
}
//全选
function checkAll(name)
{
var names=document.getElementsByName(name);
var len=names.length;
if(len>0)
{
var i=0;
for(i=0;i<len;i++)
names[i].checked=true;
}
}
//全不选
function checkAllNo(name)
{
var names=document.getElementsByName(name);
var len=names.length;
if(len>0)
{
var i=0;
for(i=0;i<len;i++)
names[i].checked=false;
}
}
//反选
function reserveCheck(name)
{
var names=document.getElementsByName(name);
var len=names.length;
if(len>0)
{
var i=0;
for(i=0;i<len;i++)
{
if(names[i].checked)
names[i].checked=false;
else
names[i].checked=true;
}
}
}
</script>
</head>
<body>
<input type="checkbox" id="ckall" onclick="checkEvent('ck','ckall')" />全选
<input type="checkbox" id="ckReserve" onclick="reserveCheck('ck','ckReserve')" />反选
<br />
<input type="checkbox" name="ck" value="1" />篮球
<br />
<input type="checkbox" name="ck" value="2" />旅游
<br />
<input type="checkbox" name="ck" value="3" />读书
<br />
<input type="checkbox" name="ck" value="4" />美食
<br />
<input type="checkbox" name="ck" value="5" />睡觉
</body>
</html>
<html>
<head>
<script type="text/javascript">
function checkEvent(name,allCheckId)
{
var allCk=document.getElementById(allCheckId);
if(allCk.checked==true)
checkAll(name);
else
checkAllNo(name);
}
//全选
function checkAll(name)
{
var names=document.getElementsByName(name);
var len=names.length;
if(len>0)
{
var i=0;
for(i=0;i<len;i++)
names[i].checked=true;
}
}
//全不选
function checkAllNo(name)
{
var names=document.getElementsByName(name);
var len=names.length;
if(len>0)
{
var i=0;
for(i=0;i<len;i++)
names[i].checked=false;
}
}
//反选
function reserveCheck(name)
{
var names=document.getElementsByName(name);
var len=names.length;
if(len>0)
{
var i=0;
for(i=0;i<len;i++)
{
if(names[i].checked)
names[i].checked=false;
else
names[i].checked=true;
}
}
}
</script>
</head>
<body>
<input type="checkbox" id="ckall" onclick="checkEvent('ck','ckall')" />全选
<input type="checkbox" id="ckReserve" onclick="reserveCheck('ck','ckReserve')" />反选
<br />
<input type="checkbox" name="ck" value="1" />篮球
<br />
<input type="checkbox" name="ck" value="2" />旅游
<br />
<input type="checkbox" name="ck" value="3" />读书
<br />
<input type="checkbox" name="ck" value="4" />美食
<br />
<input type="checkbox" name="ck" value="5" />睡觉
</body>
</html>