I have a bunch of checkboxes with a data-amount
attribute containing a value (positive or negative).
My goal is to generate a running total as the user checks each box, and then output this later on.
My code works - just curious for feedback as using filter, map and reduce seems overkill for something like this.
Thanks
const checkboxes = document.querySelectorAll('input[type=checkbox]');
const output = document.querySelector('.runningTotal');
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
const runningTotal =
Array.from(checkboxes)
.filter(i => i.checked) // remove unchecked checkboxes.
.map(i => i.dataset.amount ??= 0) //extract the amount, or 0
.reduce((total, item) => { return total + parseFloat(item)}, 0)
console.log(runningTotal)
output.innerHTML = runningTotal;
})
});
<input type="checkbox" data-amount="100"> 100
<input type="checkbox" data-amount="150"> 150
<input type="checkbox" data-amount="-50"> -50
<input type="checkbox" data-amount="10.50"> 10.50
<input type="checkbox" data-amount="0"> 0
<div class="runningTotal"></div>