- Joined
- Sep 12, 2022
- Messages
- 39
- Reaction score
- 0
If the check box is clicked, a value is to be added to the array. The array already has a loop that sums the total of its value(s). Pushing the value when the event listener is fired is the problem. I have made numerous attempts. The concept is that the checkbox should either add a value of 20 to the array or subtract a value of 20 from the array based on the event listener. I understand that the approach I have taken may have some fundamental flaws since the checkbox is unchecked by default which means the array will remain with a value of minus 20 except it is checked. What works?
JavaScript:
let arrayItems = [5, 10, 15]
let total = 0;
for (i = 0; i < arrayItems.length; i++ ) {
total += arrayItems[i];
}
console.log(total);
let checkbox = document.querySelector(".jsss");
checkbox.addEventListener('change', function() {
if (this.checked) {
arrayItems.push(20)
} else {
total -= 20
}
});
HTML:
<label for=""><input class="jsss" type="checkbox">Input 1 of many</label>