Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

display repeat issue with for Of loop

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading