用原生js写复选框 全选 不全选及小方框(checked状态改变)

时间:2020-12-17 19:40:13
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>全选</title>
<script>
window.onload=function(){
//全选
/*
var arr = document.getElementsByName('city')[0].checked=false;
//console.log(arr);
for (var i = 0; i < arr.length; i++) {

}
*/
}
/*
* 全选
*/
function checkAll(){
var arr = document.getElementsByName('city');
for (var i=0;i<arr.length;i++) {
arr[i].checked = true;
}
}
/*
* 全不选
*/

 
function uncheckAll(){
var arr1 = document.getElementsByName('city');
for (var i = 0; i < arr1.length; i++) {
arr1[i].checked = false;
}
}

/*
* 反选
*/
function encheckAll(){
var ar = document.getElementsByName('city');
for (var i = 0; i < ar.length; i++) {
ar[i].checked = !ar[i].checked;
}
}

/*
* 小方框双向选择
*/
function sel(){
//alert('888');
var arr2 = document.getElementsByName('city');
var arr3 = document.getElementById("all").checked; //true

// console.log(arr4);

for (var i = 0; i < arr2.length; i++) {
arr2[i].checked = arr3;
}


}


/*
* 获取选中的值
*/
function getVal(){
//alert(444);
var arr4 = document.getElementsByName('city');
// var arr5 = document.getElementById('getValue');
var a = [];
//console.log(arr4);
//console.log(arr5);
for (var i=0;i<arr4.length;i++) {
if(arr4[i].checked){
a.push(arr4[i].value);
}
}
alert(a.join(","));
}


</script>


</head>
<body>
<div id="list">
<li><input name="city" type="checkbox" value="1" />1.武汉</li><br />
<li><input name="city" type="checkbox" value="2" />2.孝感</li><br />
<li><input name="city" type="checkbox" value="3"/>3.宜昌</li><br />
<li><input name="city" type="checkbox" value="4"/>4.黄冈</li><br />
<li><input name="city" type="checkbox" value="5"/>5.仙桃</li><br />
<li><input name="city" type="checkbox" value="6"/>6.天门</li><br />
</div>

<div >
<input id="all" type="checkbox" name="che" onclick="sel()"/>
<input id="selectAll" type="button"  value="全选" onclick="checkAll()"/>
<input id="unselectAll" type="button"  value="全不选" onclick="uncheckAll()"/>
<input id="disSelect" type="button"  value="反选" onclick="encheckAll()"/>
<input id="getValue" type="button" value="获取选择的值" />
</div>
</body>
</html>