• Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
paulmo

set/get localStorage values from repeated form submits

15 posts in this topic

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.

1 person likes this

Share this post


Link to post
Share on other sites

Posted (edited)

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

Posted (edited)

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

Posted (edited)

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

1 person likes this

Share this post


Link to post
Share on other sites

Posted (edited)

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.

 

1 person likes this

Share this post


Link to post
Share on other sites

Posted (edited)

The text element is working as-is, sorry for the confusion, and thank you.

Edited by paulmo
clarify

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now