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>
asked Apr 21, 2015 at 19:22
user4816192
1 Answer 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
760k186 gold badges1.4k silver badges1.5k bronze badges
answered Apr 21, 2015 at 19:24
Ankur Anand
3,9142 gold badges27 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
default
Array. You're hiding the global Array constructor when you do that.