Avatar of ITsolutionWizard
ITsolutionWizard
Flag for United States of America asked on

jquery, html5, local storage

I have the jquery script below. and it is working. however, when I try to parse to html that have two same id name. It does not show the value any more. If I put one iabel name id. it works.

How can I make more than 1 label has value from the local storage codes below?


<script>
        window.onload = function() {
            retrieveData();
            retrieveSingleData();
        };
        function retrieveData() {
            for (var i = 0, len = localStorage.length; i < len; i++) {
                var key = localStorage.key(i);
                var value = localStorage[key];
                 
                if (value == "")
                {
                    value = "Missing";
                }
                $('#' + key).html(value);
                //alert(key + " => " + value);
            }
        }       
         
</script>

<label id="test1"></label>
<label id="test1"></label>

Open in new window

HTMLJavaScriptjQuery

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
Dave Baldwin

The rule is that 'id's must be unique.  JavaScript will only find the first one.  I don't know why you're getting nothing except that each 'id' should be different.
ITsolutionWizard

ASKER
Because I need to show the values on different areas. What is my options to make it happen?
ASKER CERTIFIED SOLUTION
Olaf Doschke

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Julian Hansen

Your code is looping over the localStorage domain and finding key values which it is linking to elements in the document.

You only have one key : value pairing for each key value - so this should map to a single element. I don't understand why you have two lables with the same ID - do you want to set both to the same value?

If that is the case then rather use a class or a data-attribute and then use that in your selector for setting the values.

But I would be interested to know if you really want to target more than one element for a single key:value (localStorate) pair or if it should be a single LS value to a single document element?
Your help has saved me hundreds of hours of internet surfing.
fblack61