Jump to content
paulmo

set/get localStorage values from repeated form submits

Recommended Posts

In the following script, I need to store values of desSet from repeated form submits, but they're getting over-written on every form submit, because localStorage section is nested in onclick section. Problem is I don't know how to access desSet values without being in the onclick function (because the click needs to happen to generate the value). 

How to keep every desSet value from form submits in localStorage? Also, the "description" element that desSet is in gets cleared on page refresh. How to keep that on the page? Thanks in advance for help. 

document.getElementById('btn').onclick = function() {   

..................etc..............

function localS(){        
        var valDes = document.getElementById('idDes').value;
        localStorage.setItem("desSet", valDes); 
        var desP = document.createElement("p");
        var desNode = document.createTextNode(valDes);
        desP.appendChild(desNode);
        desP.value = localStorage.getItem("desSet");
        document.getElementById("description").appendChild(desP);

}

localS();    
}; // close onclick function

 

Share this post


Link to post
Share on other sites

You will need an array to store the values, on page load you will check localstorage to see if values already exist, if yes, update the array with these values, then as more values are submitted,  add to array and localstorage.

  • Like 1

Share this post


Link to post
Share on other sites

Hi, so I've revised the first localStorage section for JSON (first code section, that's nested in main onclick function from 1st post). That is working, but localStorage is still being overwritten on every form submit (second code section below). As mentioned I want to have values stored into localStorage from multiple form submissions without overwriting. (I can see that lsCheck is probably remaining an empty array, but I don't know how to transfer the localStorage JSON to an array).  

Thanks in advance for guidance. (Also why isn't my text here line wrapping? I even copy/pasted it out of here to delete line spaces etc., then pasted it back in here. Thx)

function localS() { 
var valDes = document.getElementById('idDes').value;
    localStorage.setItem("desSet", JSON.stringify(valDes)); 
            var desP = document.createElement("p"); 
                desP.value = localStorage.getItem("desSet"); 
                var desJ = JSON.parse(desP.value);
            
    
    var desNode = document.createTextNode(desP.value); 
    desP.appendChild(desNode); 
    
    document.getElementById("description").appendChild(desP);

    }

    localS();

This section v v v is above the main onclick function (in 1st post).

<body onload = "lsCheck() ;">
     
...........etc................
  
function lsCheck() {
        lsData = [];
        if (localStorage.getItem("desSet") != null) {
            localStorage.setItem("desSet", JSON.stringify(lsData))
        }

 

Edited by paulmo

Share this post


Link to post
Share on other sites

This does not make sense to me?

var desP = document.createElement("p"); 
                desP.value = localStorage.getItem("desSet"); 
                var desJ = JSON.parse(desP.value);

if desP is a paragraph, why do you add the localstorage to its value attribute? Its a paragraph not an input, it does not use a value attribute.

What is

var desJ = JSON.parse(desP.value);

used for?

Share this post


Link to post
Share on other sites
9 hours ago, dsonesuk said:

This does not make sense to me?

Hi, I wanted to see localStorage JSON values on my page, so that's why I did this. It works.


var desP = document.createElement("p"); 
                desP.value = localStorage.getItem("desSet"); 
                var desJ = JSON.parse(desP.value);

if desP is a paragraph, why do you add the localstorage to its value attribute? See above. Its a paragraph not an input, it does not use a value attribute.

What is


var desJ = JSON.parse(desP.value);

used for? I just followed a tutorial on storing/retrieving localStorage JSON object with stringify/parse.

I've fixed the formatting of my last post, which indicates the problem I need help with, so I'm re-posting below. Thanks in advance for guidance:

I've revised the first localStorage section for JSON (1st code section below). This is nested in main onclick function (from 1st post). localStorage is working, but is being overwritten on every form submit (2nd code section below). As mentioned, I want to have values stored in localStorage from multiple form submissions without overwriting previous values. (I can see that lsCheck is probably remaining an empty array, but I don't know how to transfer the localStorage JSON to an array).

function localS() { 
var valDes = document.getElementById('idDes').value;
    localStorage.setItem("desSet", JSON.stringify(valDes)); 
            var desP = document.createElement("p"); 
                desP.value = localStorage.getItem("desSet"); 
                var desJ = JSON.parse(desP.value);
            
    
    var desNode = document.createTextNode(desP.value); 
    desP.appendChild(desNode); 
    
    document.getElementById("description").appendChild(desP);

    }

    localS();

This following code appears above (not nested in) the main onclick function (from 1st post). What I'm trying to do is keep previous localStorage data so it's not overwritten on every form re-submit:

<body onload = "lsCheck() ;">
     
...........etc................
  
function lsCheck() {
        lsData = [];
        if (localStorage.getItem("desSet") != null) {
            localStorage.setItem("desSet", JSON.stringify(lsData))
        }
Edited by paulmo
clarity

Share this post


Link to post
Share on other sites

If localstorage is not empty, you should make lsData array equal what should be array passed through localstorage, you then loop through array values recreating required element/s. On created element through form submission push values through array, and update localstorage array.

Share this post


Link to post
Share on other sites

Hi, I'm having trouble understanding your post. Would you please explain it clearly as relates to my code, and what parts I'm missing?

Edited by paulmo
clarity

Share this post


Link to post
Share on other sites
function lsCheck() {
//Array to store Multiple values
        lsData = [];

   
// if localstorage of desSet exists
                if (localStorage.desSet) {
//get array stored in storage and apply to lsData, what was in storage is also in lsData now
                    lsData = JSON.parse(localStorage.getItem("desSet"));
                    //loop through array values creating elements for hold array content
                    for (i = 0; i < lsData.length; i++) {
                        var container = document.createElement("div");
                        container.className = "img_descrip_wrap";

                        //description
                        var valDes = lsData[i]
                        var des = document.createElement('p');


                        var tex = document.createTextNode(valDes);
                        des.appendChild(tex);

                        container.appendChild(des);
                        document.body.appendChild(container);
                        
                    }
                  }
               }                          
 //At the end of btn click function after appending new image and paragraph you have these values push into array (along with values from localstorage if exits which would have been populated by onload function)   

 document.getElementById('btn').onclick = function() {

                //image
                var container = document.createElement("div");
                container.className = "img_descrip_wrap";
                //description
                var valDes = document.getElementById('idDes').value;
                var des = document.createElement('p');

                var tex = document.createTextNode(valDes);
                des.appendChild(tex);

                container.appendChild(des);
                document.body.appendChild(container);
// push (append) current value description input into array
                lsData.push(valDes);
// apply the whole array to localstorage
              localStorage.setItem("desSet", JSON.stringify(lsData));

            };

NOTE: this applies only to description value, and this has not been tested

  • Like 1

Share this post


Link to post
Share on other sites

Thank you so much, this is wonderful. I'm only able to print localStorage (lsData) values on the page with

document.getElementById("description").innerHTML = JSON.stringify(lsData, null, " ");
...as opposed to dynamically created element/container from your example above. Any idea why?
Edited by paulmo

Share this post


Link to post
Share on other sites

What code did you try? The innerHTML property works on any element.

var element = document.createElement("div");
element.innerHTML = "Text";

 

Share this post


Link to post
Share on other sites
6 hours ago, Ingolme said:

What code did you try? The innerHTML property works on any element.


var element = document.createElement("div");
element.innerHTML = "Text";

 

Don't confuse the issue, we are creating a textNode, which will work just as well if correctly used, obviously for some reason its not working, so if it is not working for creating textnode it is unlikely to work for .innerHTML either, so what is the point of bringing that into the discussion.

I have just tested the code I supplied and it WORKS without editing you have suggested, it accepts values from inputs and stores in array, you reload page it loads the array descriptions and recreate the descriptions as from before reload, Obviously you still have to create storage for img element src, there are many ways to do this, individual (as you have now) Or multi dimensional array, or object associate array (which  is probably the better method)

YOU DID REMOVE all previous scripting I presume.

Share this post


Link to post
Share on other sites

IF you stringify the array you will simply get [ "AAAAAA" ] for single array value [ "AAAAAA","BBBBBB" ] for two array values, JSON.stringify(lsData) converts to ' [ "AAAAAA","BBBBBB" ] '. While when you use lsData = JSON.parse(localStorage.getItem("desSet"));it converts it back to a readable array of values with

lsData[0] equallying "AAAAAA" and lsData[1] equallying "BBBBBB", that is what the loop does starting from 0 to less than total number of values (2) meaning 1.

 

  • Like 1

Share this post


Link to post
Share on other sites

Can or should this for loop be translated to map, and if so how to define/access lsData values?

function lsCheck() {
			lsData = [];
			
		if (localStorage.desSet) {
			lsData = JSON.parse(localStorage.getItem("desSet"));
			for (i = 0; i < lsData.length; i++) {
				var container = document.createElement("div");
				container.className = "img_descrip_wrap_ls";
				var valDes = lsData[i]
                                          .....etc........

 

Share this post


Link to post
Share on other sites

I  don't see what would be the benefit of using map() in its current state, you have all you need with current array rather than manipulate into another array.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...