Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So basically i want to count the number of checkboxes that are ticked. I get my code to the point where it counts them successfully, but I want to put in an alert that shows the number of checkboxes ticked, the code does this but doesn't show the total count, it increments the total every refresh. I just want to know how I can show a total count.

It should display the total when the radio button 'yes' is clicked.

<br />Apples
<input type="checkbox" name="fruit" />Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />
<br />Yes
<input type="radio" name="yesorno" id="yes" onchange="checkboxes()"
function checkboxes(){
    var inputElems = document.getElementsByTagName("input"),
    count = 0;
    for (var i=0; i<inputElems.length; i++) {
    if (inputElems[i].type === "checkbox" && inputElems[i].checked === true){
        count++;
        alert(count);
    }
}}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
250 views
Welcome To Ask or Share your Answers For Others

1 Answer

This should do the trick:

alert(document.querySelectorAll('input[type="checkbox"]:checked').length);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...