Check box, quantity checked / withdrawn
How do you show the number of checked boxes? I need to display some amount of the number of checked checkboxes and automatically update it for a given group. I don't know what to set the value of the arrays to do this, if I even need to. I also tried using the checked attribute but also didn't work.
var infoArray = new Array();
function userSelection(userInput) {
var itemName = userInput.name;
var itemName2 = userInput.value;
switch (itemName) {
case "sectionR":
{
switch (itemName2) {
case "repair car":
infoArray[0] = 1;
break;
case "wood work":
infoArray[0] = 1;
break;
case "explore forest":
infoArray[0] = 1;
//end of case "sectionR"
}
//end of sub switch
}
break;
case "sectionA":
{
switch (itemName2) {
case "clothing design":
infoArray[1] = 1;
break;
case "public singing":
infoArray[1] = 1;
break;
case "decorate":
infoArray[1] = 1;
//end of sub switch
}
// end of case sectionA
}
//end of main switch
}
var userOutput = new Array();
for (var i = 0; i < itemName.length; i++) {
userOutput.push(itemName[i].checked);
}
document.getElementById("selectionTotal").innerHTML = "R SECTION" + " " + "," + " A SECTION" + "<br>" +
infoArray;
//end of userSelection()
}
source to share
Instead of putting a onclick
listener for each checkbox , you can put a listener onchange
on the parent and when the event bubbles up, handle the event.
function update() {
document.getElementById('count').innerHTML =
document.querySelectorAll('#checkboxes input[type="checkbox"]:checked').length
}
<div id='checkboxes' onchange='update()'>
<input type='checkbox'>A
<input type='checkbox'>B
<input type='checkbox'>C
<input type='checkbox'>D
</div>
<div id='count'></div>
source to share
It would be helpful to see your HTML, but you can use document.querySelectorAll("input:checked").length
to get the length of a NodeList containing all the checked input elements.
Here's a quick example of how it works:
function checkThis() {
var numberChecked = document.querySelectorAll('input:checked').length;
document.getElementById('counter').innerHTML = "Number of checked boxes: " + numberChecked;
}
<form>
<input type="checkbox" name="checkthis" onclick="checkThis()" />
<br />
<input type="checkbox" name="checkthis" onclick="checkThis()" />
<br />
<input type="checkbox" name="checkthis" onclick="checkThis()" />
<br />
<input type="checkbox" name="checkthis" onclick="checkThis()" />
<br />
<input type="checkbox" name="checkthis" onclick="checkThis()" />
<br />
<input type="checkbox" name="checkthis" onclick="checkThis()" />
<br />
<input type="checkbox" name="checkthis" onclick="checkThis()" />
<br />
<p id="counter">Number of checked boxes: 0</p>
</form>
If you need to target specific checkboxes, you can simply refine your selector by adding a class or id ( input#id:checked
).
source to share