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

264
Visualizações
How can I increase the length of localstorage using my code by adding different txt1 values

I have created the below code to add my txt value to localStorage. I am able to add the value with this code but there is bit more requirement for me. I need to get different values of txt1 as different elements in local storage string. With this code I just get only one element in localStorage saying length1 (doesn't matte rhow long the txt1 is. Can anyone help me to solve the problem that how can I change the length of localstorage using txt1 values.

let btn1= document.getElementById("btn1");
btn1.addEventListener("click",function(e){
    let txt1= document.getElementById("txt1").value;
    let notes=localStorage.getItem("notes").value;
    const notesObj={txt1:txt1}

    
window.localStorage.setItem("notes",JSON.stringify(notesObj));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are simply updating the txt1 key in your object, but as you need to store multiple values, you should be using as array. Here's a small example:

    // Initializing an array with value 1
    localStorage.setItem("notes", JSON.stringify({ txt1: [1] }))
    let txt1 = 2;
    let notes = JSON.parse(localStorage.getItem("notes"));
    // Updating my next value of txt1, so that it appends to the array
    notes.txt1.push(txt1);
    localStorage.setItem("notes", JSON.stringify(notes))
    // Your output is: txt1: [1, 2]
    console.log(JSON.parse(localStorage.getItem("notes")))

In your code, you can do as:

// Initialize empty array
localStorage.setItem("notes", JSON.stringify({ txt1: [] }));
let btn1 = document.getElementById("btn1");
btn1.addEventListener("click", function (e) {
      // When the button is clicked, get the local storage data, and append the new text value
      let notes = JSON.parse(localStorage.getItem("notes"));
      notes.txt1.push(document.getElementById("txt1").value);
      localStorage.setItem("notes", JSON.stringify(notes))
      console.log(JSON.parse(localStorage.getItem("notes")))
    });
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