KingOfLeon
KingOfLeon

Reputation: 35

Number of checked checkboxes

How to rewrite this code from jQuery to vanilla JavaScript? I need to see how many checkboxes are checked. The problem is I do not know how to remove unchecked checkboxes from the total score.

$(function () {
    var countChecked = function () {
        var n = $("input:checked").length;
        $(".output").text(n);
    };
    countChecked();

    $("input[type=checkbox]").on("click", countChecked);
});

What should I do next?

var box = document.querySelectorAll('form input');
var par = document.querySelector('.output');
var great = 0;

for (var i = 0; i < box.length; i++) {
    box[i].addEventListener('click', countIt);
    function countIt() {
        for (var i = 0; i < box.length; i++) {
            if ( box[i].checked ) {
                great++
                par.innerHTML = great;
                return
            }
        }
    }
}

Upvotes: 2

Views: 122

Answers (1)

Jan Tojnar
Jan Tojnar

Reputation: 5524

You need to reset the great variable each time you count (for example by moving it inside the countIt function).

var box = document.querySelectorAll('form input');
var par = document.querySelector('.output');

function countIt() {
    var great = 0;
    for (var i = 0; i < box.length; i++) {
        if (box[i].checked) {
            great++;
        }
    }

    par.innerHTML = great;
}

for (var i = 0; i < box.length; i++) {
    box[i].addEventListener('click', countIt);
}

You can also move the countIt function definition out of the loop and the same with innerHTML setting.

Upvotes: 2

Related Questions