How can I increase the length of localstorage using my code by adding different txt1 values

Viewed 37

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));
1 Answers

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")))
    });
Related