In this short instalment I am going to demonstrate how to total all the budget items and render the totals at the bottom of the budget table.
Code for this iteration has been saved to the add-totals branch available here: https://github.com/muncey/MyBudgetFrontEnd/tree/add-totals
First I have made updates to the budgetTable to remove the contents of the tfoot element.
<table id="budgetTable">
<thead>
<tr>
<th>Item</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
Next I have added in a calculateTotals function:
const calculateTotals = () => {
let total = 0.00;
for (let i=0; i<budgetItems.length; i++) {
total+=parseFloat(budgetItems[i].amount);
}
return { item: 'Total', amount: total }
}
Notice the use of the parseFloat function which ensures each amount is treated as a number.
Then I assign the innerHTML of the tFoot element to the result of the renderRow and calculateTotals function.
const renderPage = (id) => {
document.getElementById(id).tBodies[0].innerHTML = renderRows(budgetItems);
document.getElementById(id).tFoot.innerHTML =
renderRow(calculateTotals());
}
This leaves us with a functional, but not very good looking budget tool.
In the next article I will be looking into saving the budget using local storage.
Top comments (0)