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.
JavaScript
x
33
33
1
<table id="productsTable" class="table table-striped">
2
<thead>
3
<th>
4
<div class="form-check">
5
<input class="form-check-input" type="checkbox" value="" id="checkAll">
6
<label id="labelCount" class="form-check-label" for="flexCheckDefault">
7
</label>
8
</div>
9
</th>
10
<th onclick="sortProduct()" style="cursor: pointer">Product <i class="fas fa-sort"></i></th>
11
<th onclick="sortBrand()" style="cursor: pointer">Merk <i class="fas fa-sort"></i></th>
12
<th onclick="sortSupplier()" style="cursor: pointer">Leverancier <i class="fas fa-sort"></i></th>
13
<th onclick="sortPrice()" style="cursor: pointer">Prijs <i class="fas fa-sort"></i></th>
14
<th onclick="sortQuantity()" style="cursor: pointer">Quantiteit <i class="fas fa-sort"></i></th>
15
</thead>
16
<tbody>
17
@foreach($product as $products)
18
<tr>
19
<td>
20
<div class="form-check">
21
<input name="checkbox" class="form-check-input" type="checkbox" value="">
22
</div>
23
</td>
24
<td>{{$products->title}}</td>
25
<td>{{$products->brand}}</td>
26
<td>{{$products->supplier}}</td>
27
<td>{{$products->price}}</td>
28
<td>{{$products->quantity}}</td>
29
</tr>
30
@endforeach
31
</tbody>
32
</table>
33
JavaScript
1
12
12
1
<script> let checkboxAll = document.getElementsByName('checkbox');
2
let checkboxCount = document.getElementById('labelCount');
3
4
document.getElementById('checkAll').onclick = function () {
5
let i;
6
7
for (i = 0; i < checkboxAll.length; i++)
8
{
9
checkboxAll[i].click();
10
}
11
}; <script>
12
Advertisement
Answer
You need to add an event listener on each of the checkboxes:
JavaScript
1
18
18
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<title>Parcel Sandbox</title>
5
<meta charset="UTF-8" />
6
</head>
7
8
<body>
9
<input type="checkbox" class="myCheckbox" />
10
<input type="checkbox" class="myCheckbox" />
11
<input type="checkbox" class="myCheckbox" />
12
<input type="checkbox" class="myCheckbox" />
13
14
<div id="label">0</div>
15
<script src="src/index.js"></script>
16
</body>
17
</html>
18
JavaScript
1
19
19
1
const checkboxes = document.querySelectorAll(".myCheckbox");
2
const label = document.querySelector("#label");
3
4
checkboxes.forEach((checkbox) => {
5
checkbox.addEventListener("click", () => {
6
let total = 0;
7
8
for (let i = 0; i < checkboxes.length; i++) {
9
const currentCheckbox = checkboxes[i];
10
if (currentCheckbox.checked) {
11
total += 1;
12
}
13
}
14
15
label.innerHTML = total;
16
});
17
});
18
19
Check out a working example: https://codesandbox.io/s/intelligent-nash-mbohj?file=/src/index.js