Managing Local Storage in Array: A Comprehensive Guide


Local Storage in JavaScript refers to a web browser feature that allows web applications to store data persistently on a user's device. It provides a simple key-value store where developers can save and retrieve data directly within the user's browser. Local Storage is often used to store user preferences, settings, or any data that should be available between sessions or page refreshes without the need for a server.

Local Storage in JavaScript refers to a web browser feature that allows web applications to store data persistently on a user's device. It provides a simple key-value store where developers can save and retrieve data directly within the user's browser. Local Storage is often used to store user preferences, settings, or any data that should be available between sessions or page refreshes without the need for a server.

Storage Limitations Local Storage offers a larger storage capacity compared to session storage (usually around 5-10 MB, depending on the browser). However, it's important to note that this storage is limited to the user's device and domain. Different browsers may have slightly different storage limits.

Data FormatData stored in Local Storage is always in the form of key-value pairs. Both the keys and values are stored as strings. If you need to store more complex data structures, you'll need to serialize and deserialize them, typically using JSON.

Persistent Storage Unlike session storage, data stored in Local Storage persists even after the browser is closed or the user navigates away from the page. It remains available until explicitly removed by the user, cleared by the application, or until it expires.

Same-Origin Policy Local Storage follows the same-origin policy, which means that a web page can only access data stored in Local Storage by the same domain. This restriction enhances security by preventing one website from accessing another website's data.

Simple API : Local Storage provides a straightforward API for working with data:

  • localStorage.setItem(key, value): Sets a key-value pair in Local Storage.
  • localStorage.getItem(key): Retrieves the value associated with a specific key.
  • localStorage.removeItem(key): Removes a specific key and its associated value.
  • localStorage.clear(): Clears all data stored in Local Storage for the current domain.

Events : Local Storage also provides events that notify you when data changes:storage event: Fired on a different window or tab when data is changed in Local Storage. This can be used to synchronize data between different browser instances.

sample Code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>LocalStorage Array Values</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <h1>CRUD with Local Storage</h1>
      <p>1.convert Array to strings using <mark>JSON.stringify()</mark> before storing</p>
      <p>2.convert them back to their original form using <mark>JSON.parse()</mark> after retrieving.</p>
      <hr />
      <form id="dataForm">
        <label for="dataInput">Enter Data</label>
        <input type="text" id="dataInput" />
        <button type="submit">Add Data</button>
      </form>

      <div id="output">
        <h2>Stored Data</h2>
        <ul id="dataList"></ul>
      </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

<form> Element:

  • The <form> element is used to create an HTML form that can be used to collect user input and submit it to a server for processing.
  • id="dataForm": This attribute assigns the form element a unique identifier, "dataForm," which can be used to reference this form in JavaScript or CSS.

<label> Element:

  • The <label> element is used to provide a text label for an input field. It helps users understand the purpose of the input field.
  • for="dataInput": The for attribute is used to associate the label with a specific input element. In this case, it is associated with the input element with the id attribute "dataInput."

<input> Element:

  • The <input> element is an empty element used for various types of user input.
  • type="text": This specifies that the input field is a text input where users can enter alphanumeric characters.
  • id="dataInput": Similar to the form element, this attribute assigns a unique identifier, "dataInput," to the input element. It can be used to reference this input field in JavaScript or CSS.

<button> Element:

  • The <button> element creates a clickable button that users can interact with.
  • type="text": This specifies that the input field is a text input where users can enter alphanumeric characters.
  • type="submit": This attribute specifies that this button is a submit button, which means that when clicked, it will trigger the form to be submitted. Typically, this results in the form data being sent to a server for processing.

script.js

document.addEventListener("DOMContentLoaded", function () {
  const dataForm = document.getElementById("dataForm");
  const dataInput = document.getElementById("dataInput");
  const dataList = document.getElementById("dataList");

  loadStoredData();

  dataForm.addEventListener("submit", function (e) {
    e.preventDefault();
    const data = dataInput.value.trim();
    if (data !== "") {
      addToLocalStorage(data);
      loadStoredData();
      dataInput.value = "";
    } else {
      alert("Please Enter The Data");
      dataInput.focus();
    }
  });

  //Add New Data to LocalStorage

  function addToLocalStorage(data) {
    const storedData = JSON.parse(localStorage.getItem("myData")) || [];
    storedData.push(data);
    localStorage.setItem("myData", JSON.stringify(storedData));
  }

  //Load All Data From LocalStorage
  function loadStoredData() {
    const storedData = JSON.parse(localStorage.getItem("myData")) || [];
    dataList.innerHTML = "";
    storedData.forEach((data, index) => {
      /*
      const li = document.createElement("li");
      li.textContent = data;
      dataList.appendChild(li);
      */
      let output = `
          <li>
          ${data}
          <div>
            <button class='btnEdit' data-index='${index}' >Edit</button>
            <button class='btnDelete'data-index='${index}' >Delete</button>
          </div>
           <li>
     `;
      dataList.innerHTML += output;
    });

    const delButtons = document.querySelectorAll(".btnDelete");
    delButtons.forEach((btn) => {
      btn.addEventListener("click", deleteData);
    });
    const editButtons = document.querySelectorAll(".btnEdit");
    editButtons.forEach((btn) => {
      btn.addEventListener("click", editData);
    });
  }

  //To Delete A User from LocalStorage
  function deleteData() {
    if (confirm("Are Your Sure to Delete")) {
      const index = this.dataset.index;
      const storedData = JSON.parse(localStorage.getItem("myData")) || [];
      storedData.splice(index, 1);
      localStorage.setItem("myData", JSON.stringify(storedData));
      loadStoredData();
    }
  }

  //To Modify User Data
  function editData() {
    const index = this.dataset.index;
    const storedData = JSON.parse(localStorage.getItem("myData")) || [];
    const newData = prompt("Edit Username", storedData[index]);
    if (newData !== null) {
      storedData[index] = newData.trim();
      localStorage.setItem("myData", JSON.stringify(storedData));
      loadStoredData();
    }
  }
});

The code begins by adding an event listener for the "DOMContentLoaded" event, ensuring that the JavaScript code only runs after the HTML document has been fully loaded.

DOM elements are selected and stored in variables:

  • dataForm: Represents the form element with the id "dataForm."
  • dataInput: Represents the input field with the id "dataInput."
  • dataList: Represents an element with the id "dataList," which is typically a list where the stored data will be displayed.

The loadStoredData function is called to load any existing data from Local Storage and display it in the "dataList" element.

An event listener is set up for the form's "submit" event. When the user submits the form, the callback function:

  • Prevents the default form submission behavior using e.preventDefault().
  • Retrieves the value entered in the input field, trims any leading or trailing whitespace, and checks if it's empty.
  • If the input is not empty, it calls the addToLocalStorage function to store the data in Local Storage, reloads the stored data using loadStoredData, and clears the input field.
  • If the input is empty, it displays an alert and focuses on the input field.

The addToLocalStorage function is responsible for adding new data to Local Storage. It retrieves the existing data, adds the new data, and updates Local Storage.

The loadStoredData function retrieves data from Local Storage, iterates over it, and dynamically generates list items with associated delete and edit buttons for each data item. Event listeners for delete and edit actions are added to these buttons.

The deleteData function allows users to delete a data item. It prompts for confirmation and then removes the selected data item from Local Storage. After deletion, it calls loadStoredData to refresh the data list.

The editData function enables users to modify an existing data item. It prompts for the new data, updates the item in Local Storage, and then refreshes the data list with the updated data using loadStoredData.

Overall, this code provides a simple user interface for adding, viewing, editing, and deleting data items stored in Local Storage within a web page.

To enhance the user experience, it's essential to add CSS styles to the HTML page for a visually appealing and organized presentation of content.

style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap");
* {
  margin: 0;
  padding: 0;
}

body {
  font-family: "Poppins", sans-serif;
  background-color: #f0f0f0;
}

.container {
  max-width: 800px;
  background-color: #fff;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

h1 {
  text-align: center;
  font-weight: 500;
  font-size: 18px;
  color: crimson;
  text-transform: uppercase;
  margin-bottom: 10px;
}
p {
  margin-bottom: 10px;
}
hr {
  margin-top: 20px;
  margin-bottom: 20px;
}
mark {
  font-weight: bold;
}
h2 {
  font-size: 16px;
  font-weight: 500;
  color: chocolate;
  margin-bottom: 10px;
}

label,
input {
  display: block;
  margin-bottom: 5px;
}

button {
  padding: 3px 6px;
}

#output {
  border-top: 1px solid #ccc;
  padding-top: 10px;
  margin-top: 10px;
}

#dataList {
  list-style-type: none;
}

#dataList li {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

List of Programs


JS Practical Questions & Answers


JS Practical Project