ekbayrak2 ekbayrak2 - 5 months ago 13
jQuery Question

Storing array in localstorage

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

Answer

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

       });
});
Comments