IONIC Section 4 - 4.15 Completing Basic JavaScript Logic
Click here for more videos available on our youtube channel !Now that items are generated dynamically, we need two things: clear the input fields when a new expense is added, and make the Cancel button work. To do that, we add a small clear function in the JS file:
const clear = () => {
reasonInput.value = '';
amountInput.value = '';
};
It simply assigns an empty string to value on both inputs, which wipes out anything the user typed. We then call clear() right after appending the new expense to expensesList, and we also bind it to the cancel button:
cancelBtn.addEventListener('click', clear);
Important detail: we pass clear as a reference, not clear(), so it is called only when the click event actually happens. Reloading the app, we can type "invoice" with 15 and click Cancel — the fields are cleared as expected.
Displaying a running total
To show the running total at the bottom of the app, we add a new row in the HTML with an ion-col containing a paragraph "Total expenses:" followed by a <span id="total-expenses"> that will hold the value, so we can grab it from JavaScript.
In app.js we add:
const totalExpensesOutput = document.querySelector('#total-expenses');
let totalExpenses = 0;
// inside the add-expense logic:
totalExpenses += +enteredAmount;
totalExpensesOutput.textContent = totalExpenses;
The + in front of enteredAmount converts the string coming from the input into a Number, so the addition behaves correctly instead of concatenating strings. After updating totalExpenses, we write the new value to the DOM through textContent, so it is not only kept in memory but also displayed.
Reloading the app, we enter an invoice of 6 euros, then a cinema ticket of 8 euros, and the running total appears just below: it works perfectly. The style can still be improved, especially on large screens, and that is what we will see together in the next video.