Increase the object name in localStorage to save information entered in input fields

For testing purposes only - do not use for production.

I am experimenting with storing data from 3 different input fields (text and numbers) in localStorage. My goal is to have the values increment every time the form is submitted.

However, I am encountering an issue where on the second submission, the values are being overwritten instead of continuing the incrementation sequence (e.g., from value0 to value1 and so on).

The expected outcome should be:

  1. First submit: value0, value1, value2
  2. Second submit: value3, value4, value5
  3. Third submit: value6, value7, value8 and so on.

To achieve this functionality, I have the following JavaScript code:

document.getElementById('btn').addEventListener('click', createEntry());

function createEntry(){
    const inputs = document.getElementsByTagName("input");

    let i;
    for (i = 0; i < inputs.length; i++) {
        let value = inputs[i].value; 

        localStorage.setItem(`value${i}`, JSON.stringify(value));

    }  
};

In this script, all input elements are gathered by selecting all input tags, then looping through them to assign new statements to each value before storing it in localStorage. By incrementing the item name, we avoid overwriting any previously stored values.

The corresponding HTML structure would look like this:

<div class="form">
      <input type="text" required>
      <input type="text" required>
      <input type="number" min="1" max="120" required>
      <button type="button" id="btn">Add</button>
</div>

Answer №1

Your coding approach may cause the saved values to be overwritten as the 'i' variable always resets to 0 when the function runs. There are various ways to modify your code, one suggestion is provided below:

Keeping track of the last used index

// Note: there was an error in this line where createEntry() was called
// instead of passing it as a callback.
document.getElementById('btn').addEventListener('click', createEntry);

function createEntry() {
    const inputs = document.getElementsByTagName("input");

    let i;
    let index = getNextIndex();

    for (i = 0; i < inputs.length; i++) {
        let value = inputs[i].value; 
        localStorage.setItem(`value${index}`, JSON.stringify(value));
        index++;
    }

    localStorage.setItem('nextIndex', index);
}

function getNextIndex() {
    const index = localStorage.getItem('nextIndex');
    return index ? parseInt(index) : 0;
}

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

Is there an effective way to merge two collections?

I came across an issue where I am attempting to merge two arrays that resemble the ones listed below: var participants = [ {id: 1, name: "abe"}, {id:2, name:"joe"} ]; var results = [ ...

Encountered a Socket.io issue: CONNECTION_TIMED_OUT_ERROR

I'm in the process of developing a simple HTML chat program. I've set up a node server for testing, but encountering a socket error when trying to access the HTML page. This is my first experience with Node.js and setting up a server, so it' ...

PHP encountering a bad escaped character while parsing JSON using JSON.parse

I'm encountering an issue with JSON parsing. In my PHP code, I have the following: json_encode(getTeams(),JSON_HEX_APOS); This returns a large amount of data. Sample data: To provide more clarity, let's assume I have this: my_encoded_data ...

Converting a JavaScript animation into a video through server-side processing: A step-by-step guide

Attempting to tackle a challenging task but willing to give it a shot: Our team is currently working on developing a website that enables users to generate animations using javascript and html. However, our latest client request involves uploading the cre ...

Removing automatically assigned ID information in Firestore can be achieved by following these steps:

async created () { const sn = await db.collection('forms').get() sn.forEach(v => { const { title, content } = v.data() this.forms.push({ title, content, id: v.id }) console.log(v.id) }) }, del () ...

Launching a program through a web browser - a step-by-step guide

I am looking to create a specific sequence of events: A web browser opens, and a user logs in (the exact action is not crucial) The user is then redirected to a new page where another program should automatically open This process is similar to what happ ...

Retrieving the inner content of several paragraph elements, all consolidated into a single string

I'm trying to extract the inner HTML of multiple paragraph elements from a string and I need some help. Here's an example input: let HTML = "<p class="Paragraph" >Hello, World 1!</p><p class="Paragraph" >Hell ...

Generating a dynamic triangle within a div while ensuring it fits perfectly with the maximum width

I need help with creating a responsive triangle on a web page that takes three inputs. The challenge is to adjust the size of the triangle so it fits inside a div element while maintaining the aspect ratio of the inputs. For instance, if the inputs are 500 ...

How can I convert a JSON template to HTML using AngularJS?

As someone who is just starting out with AngularJS, I am facing an issue where the HTML tags in a JSON file are not being encoded when rendered in HTML using AngularJS. Is there a specific method in AngularJS that can help with this? This is what my HTML ...

Is it possible to delete an element from an HTML form?

I'm facing an issue with removing an element from my HTML form during the loading process. The specific element in question is as follows: <input type="hidden" name="testToken" value="1000ad"></input> Here's what I've tried so ...

There seems to be a glitch in the angularjs application

This is my code for the Services.js file: angular.module('RateRequestApp.services', []). factory('rateRequestAPIservice', function($http) { var rateRequestApi = {}; rateRequestApi.getData = function () { retur ...

Is there a way to retrieve files stored on my hard drive within a webpage?

I have a large number of files stored on my hard drive, all following the same format, 2014.C1.012.012 - full name of the file. They each have unique numbers and names. I want to create a local webpage where I can organize these files into a table w ...

Techniques for implementing a JS script within a useEffect hook in a functional component

I am currently working on a useEffect hook in my project, within which there is an if-else block that includes a Javascript function called 'B1.X.Change' inside the else statement. However, I am facing difficulty binding 'B1.X.Change' t ...

The styles from the npm package are not being properly applied to the class

After creating my react npm package using webpack, I encountered an issue where the styles from the package were not being applied to classes when installed in my react project. I used style-loader in my webpack configuration, but kept getting errors sayin ...

When there is an expensive calculation following a Vue virtual DOM update, the update may not be

Currently, I am facing an issue with adding a loading screen to my app during some heavy data hashing and deciphering processes that take around 2-3 seconds to complete. Interestingly, when I removed the resource-intensive parts, the screen loads immediate ...

Tips for remaining on the current page after sending a post request using Express

I have a simple question that I haven't been able to find a satisfactory solution for. I've created a post route using express, like this: app.post('/search', function(req, res){ // Code to extract data from req and save it to the d ...

Tips for transferring objects from JavaScript/jQuery/angular to an action function

Issue at Hand: I currently have a form with 10 fields, and the challenge lies in passing these 10 values to an ASP.Net MVC Action. To tackle this, I utilize ng-click to send these values to the action which then forwards them to the database. I find myse ...

Ways to properly close open HTML tags using node.js?

Have you ever encountered a situation where user-entered content from a database or similar source only contains the opening tag without the closing tag? This can disrupt the layout of your website. Is there a way to fix this issue using Node.js on the s ...

Refresh the div by clicking it

$(window).load(function() { $("#Button").click(function() { alert('clicked') $("#div").load(" #div > *"); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script ...

What type of Javascript is required for a photo carousel that displays random images from a designated folder?

I have a minor issue that has been keeping me up at night. I can't seem to shake it off and find the right solution! Currently, I am working with Bootstrap 4 as my Framework. My task is to create a full-page Carousel that cycles through images random ...