0

I have a quiz page with multiple questions, the page shows 1 question at a time. The answers to the question are displayed in buttons. Whenever a button is pressed the second question is grabbed from the database and is shown. I have a script that puts the value of the pressed button in an array, but when the page is reloaded the array is emptied. I was told to use localstorage but I have no clue how this works, this is my code I use to store data in the array at the moment:

 $( document ).ready(function() {

           var antwoordenObject1= new Array();
            $('.btn').click(function() {
                 antwoordenObject1.push($(this).val());

                  alert("newArray contents = "+ antwoordenObject1);

            });
       });

and I found this code to put an array into localstorage but don't know how to combine these two:

var complexdata = [1,2,3,4,5,6];

// store array data to the localstorage
localStorage.setItem("list_data_key",  JSON.stringify(complexdata));

//Use JSON to retrieve the stored data and convert it 
var storedData = localStorage.getItem("complexdata");
if (storedData) {
  complexdata = JSON.parse(storedData);

}
document.write(complexdata);

2 Answers 2

2

like this:

 $( document ).ready(function() {
       var antwoordenObject1 = localStorage.getItem("antwoorden");
       antwoordenObject1 = antwoordenObject1 ? JSON.parse(antwoordenObject1) : [];
       $('.btn').click(function() {
           antwoordenObject1.push($(this).val());
           localStorage.setItem("antwoorden",  JSON.stringify(antwoordenObject1));
           alert("newArray contents = "+ antwoordenObject1);

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

1 Comment

Thanks man! you saved me a lot of time, trying to get this to work for a long time now.
1

You will have to use .setItem() and .getItem() methods of localStorage.

Note: LocalStorage can only store strings. So if you try:

var a = {
  test: "foo"
}

localStorage.setItem("test", a);

it will store [object Object] and not object itself. For arrays, it would be comma separated string.

You will have to use JSON.stringify and JSON.parse as well to communicate properly.

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.