<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../js/jquery-3.3.1.min.js"></script>
<style>
#text-box {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
</style>
</head>
<body>
<div id="text-box" style="width: 200px;height: 30px;border: red solid 1px;"></div>
<input type="checkbox" name="all" value="全选" id="select-all">全选
<input type="checkbox" name="items" value="周一" >周一
<input type="checkbox" name="items" value="周二" >周二
<input type="checkbox" name="items" value="周三" >周三
<input type="checkbox" name="items" value="周四" >周四
<input type="checkbox" name="items" value="周五" >周五
<input type="checkbox" name="items" value="周六" >周六
<input type="checkbox" name="items" value="周日" >周日
<script>
var initArr = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
var indexArr = [];
var itemArr = [];
//全选和取消全选
document.getElementById("select-all").onclick = function () {
var checkboxs = document.getElementsByName("items");
if (this.checked) {
for (var i = 0; i < checkboxs.length; i++) {
checkboxs[i].checked = this.checked;
}
indexArr = [0, 1, 2, 3, 4, 5 ,6];
fillText(initArr, indexArr, itemArr);
} else {
for (var i = 0; i < checkboxs.length; i++) {
checkboxs[i].checked = this.checked;
}
indexArr = [];
itemArr = [];
$("#text-box").html("");
}
};
//单独选中和单独取消选中
$("input[name='items']").click(function (event) {
var value = event.target.value;
if (event.target.checked) {//选中
//将选中元素对应的索引保存在数组中
var index = initArr.indexOf(value);
indexArr.push(index);
indexArr.sort();
itemArr = [];
fillText(initArr, indexArr, itemArr);
if (itemArr.length == 7) $("#select-all").prop("checked", true);
} else {//取消选中
//将选中元素对应的索引,从数组中删除
var index = initArr.indexOf(value);
var index2 = indexArr.indexOf(index);
indexArr.splice(index2, 1);
indexArr.sort();
itemArr = [];
fillText(initArr, indexArr, itemArr);
$("#select-all").prop("checked", false);
}
});
function fillText(initArr, indexArr, itemArr) {
//根据数组中的索引,生成对应的值,保存在新数组中
for (var i = 0; i < indexArr.length; i++) {
itemArr[i] = initArr[indexArr[i]];
}
//将新数组转换为字符串,并赋值到div中
$("#text-box").html(itemArr.join(","));
}
</script>
</body>
</html>
js checkbox全选和不全选
最新推荐文章于 2022-09-05 11:16:20 发布