I have multiple checkboxes on a form and I have code already that tally's how many are checked (see function showChecked). What I'm trying to do now is count how many "named" boxes are checked. For example, I want to know of "chk011","chk021", and "chk033" how many of those are checked, but I don't care about how many of the others are or not (i.e. ignore "chk001", "chk031", and "chk032"). And then return that value in a different "result". Here is my current code...
<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()"
You can store the names you want to check in an array, then, in your function, select all checked inputs and use filter to filter out the ones where the names array does not include their name attribute, then get the length of the resulting array.
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()">