Skip to content
Advertisement

Save and retrieve HTML table from localStorage

I am currently working on an app that will take data from multiple inputs, add it to an HTML table and store it to the local Storage as well. I am using HTML tables due to the fact that I wanted to implement the option to download the data as an XLSX file and for that I am using sheet.js which works with tables.

I managed to create the functions to take, store and show the data to the user but I am having a hard time with the ‘delete’ option. I would like the user to be able to delete each row but I am not sure how to update the local storage after an element is deleted.

Below is the code that I wrote for this app (please bear with me if it might look confusing but it just 1 month since I started learning Javascript).

const textInput = document.querySelector("#text-input");
const btnInput = document.querySelector("#btn-input");
const tableBody = document.querySelector("tbody");
const nameInput = document.querySelector("#name-input");
const ageInput = document.querySelector("#age-input");
const btnDownload = document.querySelector("#download");
const table = document.querySelector("#main-table");
document.addEventListener("DOMContentLoaded", getData);
btnInput.addEventListener("click", (e) => {
  e.preventDefault();
  newData();
});

// THIS FUNCTION CREATES NEW ROWS AND TABLE DATA FROM THE USER INPUT AND ADD IT TO THE MAIN TABLE

function newData() {
  let newRow = document.createElement("TR");
  let newName = document.createElement("TD");
  let newAge = document.createElement("TD");
  let newBtn = document.createElement("button");

  newRow.append(newName);
  newRow.append(newAge);
  newRow.append(newBtn);

  newBtn.innerText = "delete";
  newName.innerText = nameInput.value;
  newAge.innerText = ageInput.value;

  saveLocalName(nameInput.value);
  saveLocalAge(ageInput.value);

  tableBody.append(newRow);

  const newDeleteBtn = () => {
    newBtn.onclick = () => newRow.remove();
  };
  newDeleteBtn();
}

/* ---------- THIS FUNCTION WILL SAVE THE DATA FROM THE NAME INPUT TO THE LOCAL STORAGE --------- */

function saveLocalName(name) {
  let names;
  if (localStorage.getItem("names") === null) {
    names = [];
  } else {
    names = JSON.parse(localStorage.getItem("names"));
  }
  names.push(name);
  localStorage.setItem("names", JSON.stringify(names));
}

/* ---------- THIS FUNCTION WILL SAVE THE DATA FROM THE AGE INPUT TO THE LOCAL STORAGE --------- */

function saveLocalAge(age) {
  let ages;
  if (localStorage.getItem("ages") === null) {
    ages = [];
  } else {
    ages = JSON.parse(localStorage.getItem("ages"));
  }
  ages.push(age);
  localStorage.setItem("ages", JSON.stringify(ages));
}

/* ------- THIS FUNCTION WILL RETRIEVE THE DATA FROM THE LOCAL STORAGE ------ */

function getData() {
  let ages;
  let names;

  if (
    localStorage.getItem("ages") === null &&
    localStorage.getItem("names") === null
  ) {
    ages = [];
    names = [];
  } else {
    ages = JSON.parse(localStorage.getItem("ages"));
    names = JSON.parse(localStorage.getItem("names"));
  }

  ages.forEach((age, index) => {
    const name = names[index];
    let newRow = document.createElement("TR");
    let newAge = document.createElement("TD");
    let newName = document.createElement("TD");
    let newBtn = document.createElement("button");

    newBtn.innerText = "delete";
    newRow.append(newName);
    newRow.append(newAge);
    newRow.append(newBtn);
    newAge.innerText = age;
    newName.innerText = name;
    tableBody.append(newRow);
    const newDeleteBtn = () => {
      newBtn.onclick = () => {
        newRow.remove();
      };
    };
    newDeleteBtn();
  });
}

/* ------------------- FUNCTION TO EXPORT THE FILE AS XLSX ------------------ */

function exportXLSX(type) {
  const data = table;
  const file = XLSX.utils.table_to_book(data, { sheet: "sheet1" });
  XLSX.write(file, { bookType: type, bookSST: true, type: "base64" });
  XLSX.writeFile(file, "file." + type);
}

btnDownload.addEventListener("click", () => {
  exportXLSX("xlsx");
});
@import url("https://fonts.googleapis.com/css2?family=Poppins&display=swap");

/* SIMPLE CSS RESET */

*,
*::before,
*::after {
  box-sizing: border-box;
}

* {
  margin: 0;
}

body {
  background-color: #ffffff;
  background-attachment: fixed;
  font-family: "Poppins", sans-serif;
  line-height: 1.5;
  -webkit-font-smoothing: antialiased;
}

header {
  align-items: center;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>javascript Sandbox</title>
  <link rel="icon" href="data:;base64,=" />
  <link rel="stylesheet" href="style.css" />
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
</head>

<body>
  <form action="" id="text-input">
    <input type="text" placeholder="Enter Name" id="name-input">
    <input type="text" placeholder="Enter Age" id="age-input">
    <button id="btn-input">Submit</button>
  </form>

  <table id="main-table">
    <thead>
      <tr>
        <th>name</th>
        <th>age</th>
      </tr>
    </thead>
    <tbody>

    </tbody>
  </table>
  <button id="download">Download</button>
  <script src="script.js"></script>
</body>

</html>

I would much appreciate if someone can help with this problem that I am facing. Thank you

Advertisement

Answer

Whenever you store the row data in local storage then store it with some id like

{id : 1, value : 'abc'}

So whenever you want to delete this then first get the value from local storage via this id and then you can delete it.

Advertisement