How can I add multiple javascript objects to localStorage?

Viewed 56

I have been trying to create a function on my website that allows a user to click on a specific row of a table and the then the information on that row is saved to localstorage where it is then subsequently taken from the localstorage and printed to another table on another page so that they can save it. The issue is, I have created it so that the user clicks a table row, the information is saved in the localstorage and then it is printed to the other pages table. However, if the user wants to click on and save multiple table rows, the function is not allowing multiple objects to be saved the to the local storage. It only saves one object at a time and its the most recently clicked one.

Below is the html

<table class="table">
            <tr>
              <th>Trails</th>
              <th>Province</th>
              <th>Country</th>
            </tr>
            <tr>
              <td class="tableRow">Lion's Head</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">Pipe Track</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">Skeleton Gorge</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">Table Mountain</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">King Fisher Trail</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">Robberg Peninsula</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">Diep Walle Forest Walk</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
          </table>
        </div>

Secondly here is the html page the clicked information is being sent to

<body onload="addData()">

<table id="newTable" class="saved">
      <tr>
        <td class="saved">Trail</td>
        <td class="saved">Province</td>
        <td class="saved">Country</td>
      </tr>
    </table>

And finally, here is the javascript functions that are taking info from the first table and printing them to the second one.

let buttons = document.querySelectorAll(".save");
// console.log(buttons);

buttons.forEach((button) => {
  button.addEventListener("click", (event) => {
    const row = event.target.closest("tr");

    let newRow = row.innerText;
    let td1 = row.children[0].innerText;
    let td2 = row.children[1].innerText;
    let td3 = row.children[2].innerText;

    let td4 = td3.slice(0, -4);

    let myArray = [];
    let myObject = {
      trail: td1,
      province: td2,
      Country: td4,
    };

    myArray.push(td1, td2, td4);

    let newObj = JSON.stringify(myArray);

    localStorage.setItem("myObject", newObj);

    addData();
  });
});

//Adding the data to the new table on the saved page.
function addData() {
  let data = JSON.parse(localStorage.getItem("myObject"));
  console.log(data);
  console.log(data[0]);
  console.log(data[1]);
  console.log(data[2]);

  let table = document.getElementById("newTable");
  console.log(table);

  var row = table.insertRow(1);

  
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);

  
  cell1.innerHTML = data[0];
  cell2.innerHTML = data[1];
  cell3.innerHTML = data[2];
}

To summarise, as it stands the javascript functions are taking the text information from the clicked table row, saving it in localstorage and then creating a new table row with that information in the new table. The issue is, if the user clicks a second table row, the information in the second page is changed to the most recently clicked information, I would like it to be added to the new table instead, so that the user can save multiple trails.

Any advice is appreciated. Thanks in advance!

I have tried adding a click event listener to extract the text from a specific table row that has been clicked, then the information from that table row is added to a javascript object and saved to the local storage, I expected every time a save button was clicked the new information would be saved to the local storage as well as the old information that was clicked previously.

I thought that each time a table row would be clicked information would be added to the array in local storage, but it seems to be overwriting it each time a new row is clicked.

Thanks!

1 Answers

I'm posting this answer that @Pete left in the comments of this question.

This issue was solved by pushing the clicked objects into the array and then storing that array in localStorage.

Here is the javascript code that worked:

//Array being declared to store multiple objects in it.
let myArray = [];

//Click event listener being added to each save button on each table row.
buttons.forEach((button) => {
  button.addEventListener("click", (event) => {
    // Variable targeting the tr element the save button is contained in.
    const row = event.target.closest("tr");

    //Extracting the inner text of each child of the clicked on tr element.
    let td1 = row.children[0].innerText;
    let td2 = row.children[1].innerText;
    let td3 = row.children[2].innerText;

    // Removal of the <save></save> button with slice method.
    let td4 = td3.slice(0, -4);

    //Declaring of the object that will store the innerText of the tr elements children.
    let myObject = {
      trail: td1,
      province: td2,
      Country: td4,
    };

    console.log(myObject);

    //Here the object is being pushed into myArray
    myArray.push(myObject);

    //Here myArray is being saved to local storage as "savedTrails".
    localStorage.setItem("myObject", JSON.stringify(myArray));

    //Here an alert is being given if the user saves 1 trail, and another alert is being given if the user saves more than 1 trail.
    if (myArray.length == 1) {
      alert("There is " + myArray.length + " trail in your saved folder.");
    } else if (myArray.length > 1) {
      alert("There are " + myArray.length + " trails in your saved folder.");
    }

    addData();
  });
});

//This function is taking the saved trail information from localStorage and printing it to the new table in saveForLater page.
function addData() {
  let data = localStorage.getItem("myObject");
  let objects = JSON.parse(data);

  //Shows the objects added to the array.
  // console.log(objects);

  //This varibal selects the saved for later table.
  let table = document.getElementById("newTable");

  //Here is the for loop that iterates through the objects in local storage, and prints each saved trail to the new table in the saveForLater.html page.
  for (i = 0; i < objects.length; i++) {
    //Below is adding a new row to the table.
    var row = table.insertRow(1);

    //Below here are vriables inseting the new row cells.
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);

    //Here each cell of the row is being printed with the trail, province and country of each saved hike.
    cell1.innerHTML = JSON.stringify(objects[i].trail);
    cell2.innerHTML = JSON.stringify(objects[i].province);
    cell3.innerHTML = JSON.stringify(objects[i].Country);
    //Below is adding a new remove button that will have the functionality to remove a table rows information.
    cell4.innerHTML = `<button class="removeBtn">Remove</button>`;
  }
Related