我有一个表单上的多个复选框,我已经有代码,计数有多少被选中(见函数showChecked)。我现在要做的就是数一数有多少个命名为;复选框。例如,我想知道"chk011","chk021"one_answers"chk033"其中有多少被选中了,但我不关心其他的有多少被选中了(即忽略"chk001", "chk031"one_answers"chk032")。然后在不同的"结果"中返回那个值。这是我当前的代码…
<style>
div.floater {
position: -webkit-sticky;
position: sticky;
top: 0;
left: 65%;
width: 200px;
padding: 5px;
background-color: #cae8ca;
border: 2px solid #4CAF50;
}
</style>
<script>
showChecked();
function showChecked(){ document.getElementById("result").textContent =
"Completed = " + ((document.querySelectorAll("input:checked").length/62)*100).toFixed(0) +
'%'; }
</script>
</head>
<body>
<div class="floater"><p id="result" align="center">Completed = 0%</p></div>
<input type="checkbox" name="chk001" onclick="changeColor(); showChecked()"
<input type="checkbox" name="chk011" onclick="changeColor(); showChecked()"
<input type="checkbox" name="chk021" onclick="changeColor(); showChecked()"
<input type="checkbox" name="chk031" onclick="changeColor(); showChecked()"
<input type="checkbox" name="chk032" onclick="changeColor(); showChecked()"
<input type="checkbox" name="chk033" onclick="changeColor(); showChecked()"
您可以将要检查的名称存储在数组中,然后在函数中选择所有检查的输入,并使用filter
过滤出names
数组中不包含其name
属性的名称,然后获得结果数组的长度。
const named = ["chk011", "chk021", "chk033"]
showChecked();
function showChecked() {
document.getElementById("result").textContent = "Completed = " + ((document.querySelectorAll("input:checked").length / 62) * 100).toFixed(0) + '%';
const namedChecked = [...document.querySelectorAll("input:checked")].filter(e => named.includes(e.name)).length;
console.log(namedChecked);
}
div.floater {
position: -webkit-sticky;
position: sticky;
top: 0;
left: 65%;
width: 200px;
padding: 5px;
background-color: #cae8ca;
border: 2px solid #4CAF50;
}
<div class="floater">
<p id="result" align="center">Completed = 0%</p>
</div>
<input type="checkbox" name="chk001" onclick="showChecked()">
<input type="checkbox" name="chk011" onclick="showChecked()">
<input type="checkbox" name="chk021" onclick="showChecked()">
<input type="checkbox" name="chk031" onclick="showChecked()">
<input type="checkbox" name="chk032" onclick="showChecked()">
<input type="checkbox" name="chk033" onclick="showChecked()">