Reputation: 429
I am trying to display the values that have been stored in an array within local storage. I have been able to store the values in local storage and add other values on the click of a button but I cant retrieve the values back out and display them on a page.
This is my code that adds values to local storage.
$("#player1Link").click(function() {
if (localStorage.getItem("player1Favourite") !== null) {
var a = JSON.parse(localStorage.getItem('player1Favourite'));
if (a.indexOf(chosenPlayerId) === -1) {
a.push(chosenPlayerId);
localStorage.setItem('player1Favourite', JSON.stringify(a));
alert("Pushed in");
} else {
alert("Already in favourites");
}
} else {
var a = [];
a.push(chosenPlayerId);
localStorage.setItem('player1Favourite', JSON.stringify(a));
}
})
I want to be able to click a button to retrieve the values and display them on the page but I can figure out the code to go in this function.
$("#playerRetrieve").click(function() {});
If anyone could help it would be much appreciated.
Upvotes: 3
Views: 213
Reputation: 2331
I made a jsfiddle, it seems to work there: jsfiddle
try:
localStorage.getItem('player1Favourite');
or:
localStorage.player1Favourite
You might want to have a look at: this topic or at Mozilla
Upvotes: 2
Reputation: 1261
I'm not exactly sure I understand you correctly, because if you just want to retrieve the values you can use the same code, just remove the insertion from your code and change the jQuery selector.
$("#playerRetrieve").click(function() {
if (localStorage.getItem("player1Favourite") !== null) {
var a = JSON.parse(localStorage.getItem('player1Favourite'));
// Do what you want with the values, which are now in a.
}
});
Upvotes: 1