This Code works to Give me stored cars Name
<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>
</html>
But how can i get the stored car names in form of an array and display it. I tried modifying the readCarNames() function in two ways but none of them worked. I searched but everywhere it's all about passing the object and storing which i'm able to do but not able to retrieve it in form of an array and then print it
here is what i tried to work out but didn't worked
function readCarNames(){
if(window.localStorage){
var carNames=localStorage.getItem("carNameKey");
var resultCarNames[]=JSON.parse(carNames);
resultCarNames.toString();
document.getElementById("displayCarNames").innerHTML = resultCarNames;
}
and the second one that i attempted but didn't worked .
function readCarNames(){
if(window.localStorage){
var carNames=localStorage.getItem("carNameKey");
carNames = JSON.parse(carNames);
var resultCarNames[];
for (i=0;i<carNames.length;i++){
resultCarNames.push(carNames[i]);
}
resultCarNames.toString();
document.getElementById("displayCarNames").innerHTML = resultCarNames;
}
Aucun commentaire:
Enregistrer un commentaire