JavaScript-复选框处理
2022-06-21 本文已影响0人
测试探索
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type = "text/javascript" src="index.js"></script>
</head>
<body>
<form>
<input type="checkbox" name="interest" value="1"><label>游泳</label>
<input type="checkbox" name="interest" value = "2"><label>爬山</label>
<input type="checkbox" name="interest" value = "3"><label>看书</label>
<input type="checkbox" name="interest" value = "4"><label>听歌</label>
<input type="button" id = "btn1" value = "全选" onclick="checkInterest()">
<input type="button" value = "反选" onclick="checkInterest1()">
</form>
</body>
</html>
index.js
var flag = true;
//全选与取消全选功能
function checkInterest(){
var interest = document.getElementsByName("interest");
for(i=0;i<interest.length;i++){
//等于true代表选中
interest[i].checked = flag;
}
if(flag){
document.getElementById("btn1").value = "取消全选";
}else{
document.getElementById("btn1").value = "全选";
}
flag = !flag;
}
//反选功能
function checkInterest1(){
var interest = document.getElementsByName("interest");
for(i=0;i<interest.length;i++){
//等于true代表选中
interest[i].checked = !interest[i].checked;
}
}