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>
3
  • possible duplicate of Storing Objects in HTML5 localStorage Commented Apr 21, 2015 at 19:24
  • 1
    Don't use the variable name Array. You're hiding the global Array constructor when you do that. Commented Apr 21, 2015 at 19:27
  • You say it doesn't give you the desired result. We need to know the desired result and actual result. Commented Apr 21, 2015 at 19:35

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.