3

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.
    }
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.