Skip to content

How do I sum all checkboxes in javascript / jquery and how can it be dynamically displayed in a bootstrap label?

I am trying to get it dynamic but I just can’t get it done.

The label must add up all checkboxes and if a checkbox is checked or unchecked the total count number must be up or down.

If one checkbox is clicked and it is checked, the label must go up with +1, if the checkbox is clicked and the checkbox is unchecked then the label must go off with -1.

    <table id="productsTable" class="table table-striped">
            <div class="form-check">
                <input class="form-check-input" type="checkbox" value="" id="checkAll">
                <label id="labelCount" class="form-check-label" for="flexCheckDefault">
        <th onclick="sortProduct()" style="cursor: pointer">Product <i class="fas fa-sort"></i></th>
        <th onclick="sortBrand()" style="cursor: pointer">Merk <i class="fas fa-sort"></i></th>
        <th onclick="sortSupplier()" style="cursor: pointer">Leverancier <i class="fas fa-sort"></i></th>
        <th onclick="sortPrice()" style="cursor: pointer">Prijs <i class="fas fa-sort"></i></th>
        <th onclick="sortQuantity()" style="cursor: pointer">Quantiteit <i class="fas fa-sort"></i></th>
        @foreach($product as $products)
                    <div class="form-check">
                        <input name="checkbox" class="form-check-input" type="checkbox" value="">

    <script> let checkboxAll = document.getElementsByName('checkbox');
    let checkboxCount = document.getElementById('labelCount');
    document.getElementById('checkAll').onclick = function () {
        let i;
            for (i = 0; i < checkboxAll.length; i++)
    };  <script>


You need to add an event listener on each of the checkboxes:

<!DOCTYPE html>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <input type="checkbox" class="myCheckbox" />
    <input type="checkbox" class="myCheckbox" />
    <input type="checkbox" class="myCheckbox" />
    <input type="checkbox" class="myCheckbox" />
    <div id="label">0</div>
    <script src="src/index.js"></script>
const checkboxes = document.querySelectorAll(".myCheckbox");
const label = document.querySelector("#label");
checkboxes.forEach((checkbox) => {
  checkbox.addEventListener("click", () => {
    let total = 0;
    for (let i = 0; i < checkboxes.length; i++) {
      const currentCheckbox = checkboxes[i];
      if (currentCheckbox.checked) {
        total += 1;
    label.innerHTML = total;

Check out a working example: