0

When I'm Trying to Store Array using local Storage it's giving me not the desired Result Why ?.. Here is the code that i've written

   <html>
    <head>
        <script type="text/javascript">
            var Array=[];
            function addToList(){
                var Name=document.getElementById('Name');
                Array.push(Name.value);
                if(window.localStorage){
                    localStorage.setItem("name",Name);
                }

            }

        </script>
    <title>Local Storage Demo</title>
    </head>
    <body>
    <h1>Local Strorage</h1>
    <div>
        <input type="text" id="Name" name="Name"> </input>
        <button onclick="addToList()">Add</button>

    </div>
    </body>
    </html>
  • possible duplicate of [Storing Objects in HTML5 localStorage](http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) – WayneC Apr 21 '15 at 19:24
  • 1
    Don't use the variable name `Array`. You're hiding the global Array constructor when you do that. – Pointy Apr 21 '15 at 19:27
  • You say it doesn't give you the desired result. We need to know the desired result and actual result. – Nick Apr 21 '15 at 19:35

1 Answers1

1

This has already so many answers on the Stack Overflow. Learn to Search things Properly anyway

You need to use JSON.stringify. That turns an object in to a JSON text and stores that JSON text in a string.

And also while retrieving value you need to parse it using JSON.parse which turns json text back into an object.

Here is one sample code that will help you

<html>
<head>
    <script type="text/javascript">
        var carArray=[];
        function addToListCarArray(){
            var newCarName=document.getElementById('carName');
            carArray.push(newCarName.value);
            if(window.localStorage){
                localStorage.setItem("carNameKey",JSON.stringify(carArray));
            }
        }

        function readCarNames(){
            if(window.localStorage){
                var carNames=localStorage.getItem("carNameKey");
                carNames = JSON.parse(carNames);
                for (i=0;i<carNames.length;i++){
            alert(carNames[i]);
        }
      }
    }
    </script>
<title>Local Storage Demo</title>
</head>
<body>
<h1>Demo of Local Strorage</h1>
<div>
    <input type="text" id="carName" name="carName"> </input>
    <button onclick="addToListCarArray()">Add Car</button>
    <button onclick="readCarNames()">Display</button>
    <p id="displayCarNames"></p>
</div>
</body>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ankur Anand
  • 3,873
  • 2
  • 23
  • 44