Hello @ abhittac,
You have create the array everytime the method is called and you should call JSON.stringify(Array) on storing the item and JSON.parse(string_from_localStore) when loading the item from localStore.
But you should wrap the stringify in an try and catch block, because it can be some reasons when the json string is not well formed that your stringify method crashes the function and it stops working.
Sample code:
<html>
<body>
<form>
<input id="textInput" type=text>
<input type=button onclick="myFunction()" value="Add Number"/>
</form>
<div id="output"><div>
<script>
var myFunc = function() {
//load it at first from localstorage
var sports = ["soccer", "baseball"];
var localSports = [];
try {
localSports = JSON.parse(window.localStorage.getItem('sportskey'));
if( localSports == null)
localSports = sports;
} catch(ex) {
console.log("something wrong");
localSports = sports; //fallback
}
var newSport = document.getElementById('textInput').value;
localSports.push(newSport); //this is an array
//insert the array with JSON.stringify so you can take it later out and rework with it
window.localStorage.setItem("sportskey", JSON.stringify(localSports));
output.innerHTML = window.localStorage.getItem('sportskey');
};
</script>
</body>
</html>
You can refer to above code for you query.
Hope it helps!!
Thank you!!