使用JavaScript实现CheckBox 全选、取消全选、当选择框全部选上时,全选框自动勾上、当选择框部分勾上时,全选框自动取消勾上
<html>
<head>
<title>JavaScript实现全选和反全选- hzsasheng_阿方索_开发天空
<script type="text/javascript">
function checkAll(name) {
var el = document.getElementsByTagName('input');
var len = el.length;
for(var i=0; i<len; i++) {
if((el[i].type=="checkbox") && (el[i].name==name)) {
el[i].checked = true;
}
}
}
function clearAll(name) {
var el = document.getElementsByTagName('input');
var len = el.length;
for(var i=0; i<len; i++) {
if((el[i].type=="checkbox") && (el[i].name==name)) {
el[i].checked = false;
}
}
}
function checkIsAllSelect(name)
{
var el = document.getElementsByTagName('input');
var len = el.length;
var isAllSelect = true ;
for(var i=0; i<len; i++) {
if((el[i].type=="checkbox") && (el[i].name==name)) {
if( el[i].checked == false ) { isAllSelect = false ; }
}
}
if( isAllSelect == true )
document.getElementById('test1').checked = true ;
else
document.getElementById('test1').checked = false ;
}
</script>
</head>
<body>
<input type="checkbox" name="test1" id="test1" value="" οnclick="if(this.checked==true) { checkAll('test'); } else { clearAll('test'); }" /> 全选开关
<input type="checkbox" name="test" value="a" οnclick="checkIsAllSelect('test')" /> a
<input type="checkbox" name="test" value="b" οnclick="checkIsAllSelect('test')"/> b
<input type="checkbox" name="test" value="c" οnclick="checkIsAllSelect('test')"/> c
<input type="checkbox" name="test" value="d" οnclick="checkIsAllSelect('test')"/> d
</body>
</html>