I want to make a counter that shows how many checkboxes are in the checkbox list in the html page. My code is as below. The counter that I show in HTML is not updated, why?
I may not be able to capture the checkbox value in the if block.
var clicks = 0;
function checkboxes() {
var inputElems = document.getElementsByTagName("input"),
for (var i = 0; i < inputElems.length; i ) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true) {
clicks = 1;
document.getElementById("clicks").innerHTML = clicks;
} else {
clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
}
}
}
<div >
<ol>
<li>
<label for="random-1" >
<input id="random-1" type="checkbox" name="mycheckbox" value=578080>
xxxx
</label>
</li>
<li>
<label for="random-1" >
<input id="random-1" type="checkbox" name="mycheckbox" value=1234>
xxxx
</label>
</li>
<li>
<label for="random-1" >
<input id="random-1" type="checkbox" name="mycheckbox" value=567>
xxxx
</label>
</li>
</ol>
</div>
<p>clicks: <a id="clicks">0</a></p>
CodePudding user response:
- Seems you haven't called checkboxes() method.
- The logic you've written seems to be wrong. Here is the working solution
document.getElementById("checkbox-list").addEventListener("click", checkboxes);
function checkboxes() {
var inputElems = document.getElementsByTagName("input");
var clicks = 0;
for (var i = 0; i < inputElems.length; i ) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true) {
clicks = 1;
}
document.getElementById("clicks").innerHTML = clicks;
}
}
<div >
<ol id="checkbox-list">
<li>
<label for="random-1" >
<input id="random-1" type="checkbox" name="mycheckbox" value=578080>
xxxx
</label>
</li>
<li>
<label for="random-1" >
<input id="random-2" type="checkbox" name="mycheckbox" value=1234>
xxxx
</label>
</li>
<li>
<label for="random-1" >
<input id="random-3" type="checkbox" name="mycheckbox" value=567>
xxxx
</label>
</li>
</ol>
</div>
<p>clicks: <a id="clicks">0</a></p>