checked的简单练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>全选练习</title>
</head>
<body>
<form action="">
你爱好的运动是?
<input type="checkbox" id="allBox">全选/全不选
<br>
<input type="checkbox" class="ball" id="lan" value="篮球">篮球
<input type="checkbox" class="ball" id="yu" value="羽毛球">羽毛球
<input type="checkbox" class="ball" id="zu" value="足球">足球
<input type="checkbox" class="ball" id="ping" value="乒乓球">乒乓球
<br />
<input type="button" id="all" value="全选">
<input type="button" id="notAll" value="全不选">
<input type="button" id="fan" value="反选">
<input type="button" id="turn" value="提交">
</form>
<script>
window.onload = function(){
var ball = document.getElementsByClassName("ball");
var all = document.getElementById("all");
all.onclick = function(){
//ball变成了数组,遍历一遍数组
for(var i=0 ; i<ball.length ; i++){
//获取checked属性来设置checkbox多选框的选中状态
//语法:chaneckboxObject(对象).checked = true | false
//console.log(ball[i].checkbox); 选中返回true,没有就返回false
ball[i].checked = true;
if(ball[i].checked){
allBox.checked = true;
}
}
}
var notAll = document.getElementById("notAll");
notAll.onclick = function(){
for(var i=0;i<ball.length;i++){
ball[i].checked = false;
if(!ball[i].checked){
allBox.checked = false;
}
}
}
var fan = document.getElementById("fan");
fan.onclick = function(){
allBox.checked = true;
for(var i=0;i<ball.length;i++){
/*
if(ball[i].checked == true){
ball[i].checked = false;
}else{
ball[i].checked = true;
}
*/
//直接设置取反就可以设置反选
ball[i].checked = !ball[i].checked;
if(!ball[i].checked){
allBox.checked = false;
}
}
}
var turn = document.getElementById("turn");
turn.onclick = function(){
for(var i=0;i<ball.length;i++){
if(ball[i].checked == true){
alert(ball[i].value)
}
}
}
var allBox = document.getElementById("allBox");
allBox.onclick = function(){
for(var i =0;i<ball.length;i++){
ball[i].checked = this.checked;
//用allBox的true和false来控制ball的选中状态
}
}
//只要有一个没选中,就返回false
for(var i=0;i<ball.length;i++){
ball[i].onclick = function(){
allBox.checked = true;
for(var j=0;j<ball.length;j++){
if(!ball[j].checked){
allBox.checked = false;
break;
}
}
}
}
};
</script>
</body>
</html>