Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
Table contents disappear on refresh

I'm trying to make a money tracker but every time I refresh they disappear. Anyone know how I can use local storage to make them stay? I've tried using local storage but I can't wrap my head around it and it is very confusing for me. Code Pen - https://codepen.io/jordandevelops/pen/wvPWzxL

    const table = document.getElementById('contentTable'),
inputText = document.getElementById('inputText'),
inputPrice = document.getElementById('inputPrice'),
inputDate = document.getElementById('inputDate'),
form = document.getElementById('form');

form.addEventListener('submit', (e) => {
    e.preventDefault();
    addNewItem();
});

function addNewItem(){
    if(inputPrice.value == ''){
        alert('Error, please enter price of purchase.');
        return;
    }
    if(inputDate.value == ''){
        alert('Error, please enter date of purchase.');
        return;
    }
    let newTr = document.createElement('tr');
    let newTd1 = document.createElement('td');
    let newTd2 = document.createElement('td');
    let newTd3 = document.createElement('td');
    table.appendChild(newTr);
    newTr.appendChild(newTd1);
    newTr.appendChild(newTd2);
    newTr.appendChild(newTd3);
    newTr.classList.add('createdTr')
    newTd1.classList.add('tdName');
    newTd2.classList.add('tdPrice');
    newTd3.classList.add('tdDate');
    newTd1.innerText = inputText.value;
    newTd2.innerText = `$${inputPrice.value}`;
    newTd3.innerText = inputDate.value;
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In local storage, you store the data structure in JSON format (not the HTML that contains the data).

To store data:

function addNewItem(){
  //... check and validate the input like you do
  // grab the current local storage or create an empty container
  let theData = localStorage.get('theData') || "[]"; 
  theData = JSON.parse(theData); // get it into object format
  //add to it
  theData.push({text: inputText.value, price: inputPrice.value, date: inputDate.value});
  // store that back into local storage as a string
  localStorage.set('theData', JSON.stringify(theData));
  //... continue on with your code

To retrieve the data, do it on page load

document.addEventListener('DOMContentLoaded', () => {
  let theData = localStorage.get('theData') || "[]";
  JSON.parse(theData).forEach(d => {
     // ... this is where you take the existing local storage list and populate it into your HTML. 
     // You can leverage your existing addNewItem function but you'll need to update it to allow for sending input directly into it.
  })
about 4 years ago · Juan Pablo Isaza Relatório

0

Local storage can work ok, but I'd recommend using IndexedDB if you want to store data like this.

IndexedDB is even more complicated than local storage in some ways, but there's a great library called "Dexie" that makes it a lot easier. You can see it here: https://dexie.org/

Using Dexie, you can save, restore and query your data. It will take a little time to experiment with and learn how to do, but it will be a great tool to have in your toolbox.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda