Storing past entries in a local storage using JavaScript

Currently, I am developing a JavaScript program that involves 3 input boxes. The program is designed to display whatever is typed into each input box on the page. To store and re-display previous submissions, I have implemented local storage. However, I encountered an issue where using setItem() overrides all the previous submissions. Can someone suggest an alternative method to preserve prior submissions?

While attempting to create a JSFiddle link with my code for reference, I faced errors in the console on the JSFiddle platform. Surprisingly, the code functions perfectly fine locally. Below, you will find the raw code with detailed comments.

Note: This inquiry is distinct from the discussion on session storage found here.

Code:

"use strict";

// A self-invoking function encapsulates the entire code to avoid global scope pollution.
(function() {
    var storageArray = [];
    window.onload = retrieve();

    function Credential(name, address, email) {
      this.name = name;
      this.address = address;
      this.email = email;
    }
    var button = document.getElementById("doit");
    button.onclick = function() {

      // Obtain values from the form fields
      var name = document.getElementById("name").value;
      var address = document.getElementById("address").value;
      var email = document.getElementById("email").value;

      // Create a new data object representing the input values
      var data = {
        name, address, email
      };

      // Display the new data object on the page
      writeRowToPage(data, output);
      
      // Store the object in localStorage without overwriting previous data
      storageArray.push(data);
      window.localStorage.setItem("storageArr", JSON.stringify(storageArray));
    }

    /* This function writes a single submission row onto the page based on the dataObject provided */
    function writeRowToPage(dataObject, element) {
      var s = "<div class=\"info\">";

      s += '<div class="nameDiv">';
      if (dataObject.name !== 'undefined') {
        s += dataObject.name;
      }
      s += '</div><div class="addrDiv">';
      if (dataObject.address !== 'undefined') {
        s += dataObject.address;
      }
      s += '</div><div class="emailDiv">';
      if (dataObject.email !== 'undefined') {
        s += dataObject.email;
      }
      s += '</div></div>';

      element.innerHTML += s;
    }


    /* Retrieve existing data from localStorage upon page load, convert it into data objects,
       then display these objects on the page using writeRowToPage() */
    var credString = window.localStorage.getItem("storageArr");
    var credList = JSON.parse(credString);

    function retrieve() {
      for (var i = 0; i < credList.length; i++) {
        var newCred = new Credential(credList[i].name, credList[i].address, credList[i].email);
        storageArray.push(newCred);
        writeRowToPage(newCred, 'output');
      }
    }
  })();
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.428571429;
color: #333;
}
.button {
border: 1px solid #888888;
color: #ffffff;
font-family: Arial;
font-size: 15px;
font-weight: bold;
font-style: normal;
height: 30px;
width: 82px;
line-height: 14px;
padding: .5em;
text-align: center;
background-color: #614C26;
}
.button:hover {
border: 2px solid #000;
}
label {
display: inline-block;
width: 5em;
}
.info div {
display: inline-block;
width: 10em;
}
.infoHead {
font-weight: bold;
border-bottom: 1px solid gray;
width: 30em;
}
<!doctype html>
<html>

<head>

  <link rel="stylesheet" href="css/cscie3.css">
</head>

<body>
  <label for="name">Name</label>
  <input type="text" size="40" id="name">
  <br>
  <label for="address">Address</label>
  <input type="text" size="40" id="address">
  <br>
  <label for="email">Email</label>
  <input type="text" size="40" id="email">
  <br>
  <button id="doit" class="button">Save</button>

  <h2>My Records</h2>
  <div id="output">
    <div class="info infoHead">
      <div>Name</div>
      <div>Address</div>
      <div>Email</div>
    </div>
  </div>

  <script tyle="text/javascript" src="js/hw2b_v3.js"></script>
</body>

</html>

Answer №1

Each time the page is loaded, a new array is created and new values are set in localStorage. To address this issue, follow these steps:

"use strict";

// Encapsulate everything in a self-invoking function to avoid polluting the global scope.
(function(){
    var storageArray = localStorage["storageArr"] ? JSON.parse(localStorage["storageArr"]) : [];
    window.onload = retrieve();
    function Credential (name, address, email) {
      this.name = name;
      this.address = address;
      this.email = email;
    }
    var button = document.getElementById("doit");
    button.onclick = function(){
        // This function executes when the Save button is clicked.

        // Step #1 - Retrieve values from the form
        var name = document.getElementById("name").value;
        var address = document.getElementById("address").value;
        var email = document.getElementById("email").value;

        // Step #2 - Create a new data object
        var data = {name, address, email};

        // Step #3 - Write the new data object to the page
        writeRowToPage(data, output);

        // Step #4 - Store the object in localStorage
        storageArray.push(data);
        window.localStorage.setItem("storageArr",JSON.stringify(storageArray));
    }

    /* Function to write a row of data to the page */
    function writeRowToPage(dataObject, element) {
        var s = "<div class=\"info\">";

        s+='<div class="nameDiv">';
        if (dataObject.name !== 'undefined') {
            s+=dataObject.name;
        }
        s+= '</div><div class="addrDiv">';
        if (dataObject.address !== 'undefined') {
            s+=dataObject.address;
        }
        s+= '</div><div class="emailDiv">';
        if (dataObject.email !== 'undefined') {
            s+=dataObject.email;
        }
        s+= '</div></div>';

        element.innerHTML += s;
    }

     /* Retrieve existing data from localStorage on page load */
     function retrieve() {
    var localMemory = window.localStorage.getItem("localArr");
    var parsedLocalMemory = JSON.parse(localMemory);
    
    if (parsedLocalMemory != null){
        for (var i = 0; i < parsedLocalMemory.length; i++) {
            var nextPerson = new AddrBookEntry (parsedLocalMemory[i].name, parsedLocalMemory[i].addr, parsedLocalMemory[i].email);
            writeRowToPage(nextPerson, output);
        }
    }
}
})(})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Darken the entire webpage and gradually fade in a specific div element using Jquery

Currently, I am working on implementing the following functionality: - When a link is clicked, it should trigger a function to show a DIV (#page-cover) that will dim down the entire background. This div has a z-index of 999. - Following the dimming effect, ...

Whenever I click the left mouse button, the website crashes

Why does clicking the left mouse button make the website scroll down? Any ideas for a solution? Check out the link here: I've tried everything since I just started working on my website. Be prepared to be shocked when you see the source code HAHAHHA ...

Utilizing the Data Fetched from a Factory GET Request in an AngularJS Controller

Recently, I developed an Angular factory specifically designed for fetching JSON data. Utilizing the $resource alongside the get method has allowed me to successfully retrieve a JSON object from the server. Within this object are multiple child objects tha ...

Mean stack authentication issue: missing token

Overview: Currently, I'm in the process of developing an application that utilizes node/express for the backend, mongo as the database, and angular for the frontend. User authentication is handled through jsonwebtoken, where a token is stored in local ...

Utilize AngularJS to create a concealed input field

Currently utilizing angularjs, you can find the code at this link Desired Outcome: When the add button is clicked, I want the value of $scope.todotest to appear along with the text in the textbox. Issue Faced: Upon adding for the first time, the date d ...

What is the best way to create a dynamic JavaScript counter, like one that counts the world's population

Can someone guide me on creating a real-time JavaScript count-up feature that doesn't reset when the page reloads? Any tips or examples similar to would be much appreciated. Thank you! ...

Display a compilation either in the backend or the frontend

I'm fairly new to NodeJS and I could really use some advice. I currently have a webpage that displays a list of users, which is retrieved from a collection using Mongoose. I am aware of two different ways to display this list: 1) One option is to que ...

Web scraping with Cheerio in Node.js sometimes yields undefined results

When attempting to extract data from NSE website, I initially tried using the inspect element console: (Edited the question) https://i.sstatic.net/Xq8mZ.png objs = $('div[class="table-wrap"] > table > tbody > tr > td').slic ...

Add the item to an array to store its state

I have a state variable that is initially set as an empty array const [boxes, setBoxes] = useState([]); const [showAddGalley,setShowAddGalley]=useState({galleyNo:""}); I created a function to handle form submissions, where I want to update the b ...

Node.js encountered an error: Module 'mongoose' not found

C:\Users\Alexa\Desktop\musicapp\Bots\Soul Bot>node bot.js Node.js Error: Missing module 'mongoose' at Function._resolveFilename (module.js:334:11) at Function._load (module.js:279:25) at Module.requir ...

Functionality Issue: Submit Button Not Working on Designed Form Select

Through dedication and hard work, I managed to create a customized form with images that display correctly in Firefox, Chrome, and Internet Explorer's compatibility mode. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w ...

Accessing Wikipedia's API in order to retrieve search query results

I'm currently working on incorporating Wikipedia's API into my web page to execute a search query and display the results. Here is the progress I've made so far: "use strict"; $(document).ready(function(){ function searchWikipedia(searchC ...

What is the process of integrating data retrieved from an SQL query into a Pug template using Express and MySQL?

Currently, I am in the process of developing a basic web application that will initially show a list of bus route numbers and names upon landing on the page. My tech stack includes MySQL integrated with Express and Pug. Below is the server-side code snippe ...

The order of event handlers in jQuery

I am currently setting up event binding for a text element dynamically. Take a look at the following code snippet: <input type="text" id="myTxt" /> <script type="text/javascript"> function attachEvent1(element){ element.keyup(func ...

Learn how to display or conceal the HTML for 'Share this' buttons on specific routes defined in the index.html file

Currently, I am in the process of updating an existing Angular application. One of the requirements is to hide the "Share this buttons" on specific routes within the application. The "Share" module typically appears on the left side of the browser window a ...

"Silently update the value of an Rxjs Observable without triggering notifications to subscribers

I'm currently working on updating an observable without alerting the subscribers to the next value change. In my project, I am utilizing Angular Reactive Forms and subscribing to the form control's value changes Observable in the following manner ...

Overflow: Truncating text with an ellipsis in the center

Seeking a CSS-only solution for adding an ellipsis in the middle of a string when it exceeds its container. I have tried splitting the container in half, trimming the first half with a wrapper on a whole letter and adding an ellipsis to the front of the s ...

Tips for extracting data from JSON values

My JSON Data Display let foodData = [{ meal_com_id: "1", name_company: "PeryCap", image: "https://shopgo.in/upload/1545849409-1518284057-Untitled-nn1.png", status: "1", description: "sdvaebfvhjaebfber itnwiuore tg5ykrgt wiretgi34 tgi3rgt ...

Implement a feature in Vuejs where the user can easily move to the next field by simply

I need help implementing a feature that moves the focus to the next field when the enter key is pressed. I've tried the following code, but it's not working as expected. When I added a debugger in the focusNext method inputs[index + 1].focus();, ...

Using the $timeout function inside an AngularJS factory

In my project, I decided to utilize an AngularJS factory to create new instance models. Each model includes a progress value that is manipulated based on user actions such as "start", "pause", and "stop". app.factory('ModelA', ['$timeout&ap ...