on this expense tracker every time I submit my form the results repeat . I’m thinking it has something to do with loop or the page refresh.
function addExpense(e) {
e.preventDefault();
// take the values from my form
// add them to my local storage to avoid losing data
let name = document.getElementById("name").value
let selection = document.getElementById("expenseMenu").value
let amount = document.getElementById("amount").value
const expense = {
name,
selection,
amount,
}
if (localStorage.getItem("ex_data") === null) {
localStorage.setItem("ex_data", "[]")
}
let array = JSON.parse(localStorage.getItem("ex_data"))
array.push(expense)
localStorage.setItem("ex_data", JSON.stringify(array))
document.getElementById('expForm').reset();
display()
}
function display() {
let display = document.getElementById("display")
let results = JSON.parse(localStorage.getItem("ex_data"))
for (const info of results) {
display.innerHTML += `
<tr>
<td>${info.name}</td>
<td>${info.selection}</td>
<td>${info.amount}</td>
</tr>`
}
}
I’m guessing every time I submit the for of loop is iterating over the array from the beginning each time and repeating the list as a whole
>Solution :
You’re looping through the entire array, concatenating to the output DIV, so you never remove the old contents before adding everything again.
Instead of concatenating to the innerHTML, create a string with all the HTML you want, and replace the innerHTML with it.
function display() {
let display = document.getElementById("display")
let results = JSON.parse(localStorage.getItem("ex_data"))
let html = '';
for (const info of results) {
html += `
<tr>
<td>${info.name}</td>
<td>${info.selection}</td>
<td>${info.amount}</td>
</tr>`
}
display.innerHTML = html;
}