Store items in sessionStorage that has ben pushed in another function

46 Views Asked by At

I've a slight problem with my code.

I have an array that stores values and i need to store them into sessionStorage.

document.getElementById("submit-button").addEventListener("click", book, false);

var array = new Array;

function book()
{

 var seat;

 // value in label that is changed everytime i click on a element.
 seat = document.getElementById("label").innerHTML;

 // Put it in a global array
 array.push(seat);
 window.sessionStorage.setItem("items", JSON.stringify(array));


 booked(seat);


}

and in load() function:

function load()
 {
  var storedArray = JSON.parse(window.sessionStorage.getItem("items"));


  for (var i = 0; i < storedArray.length; i++)
  {
    var str1 = "seat";
    var str2 = storedArray[i];


    var number = document.getElementById(str1.concat(str2));
    var context = number.getContext("2d");
    context.fillStyle = 'red';
    context.fillRect(0,0, seat18.width, seat18.height);
  }

 }

But my problem is that every time i call book() function, the array resets itself and pushing the new value. And in load() function, the storedArray in only register the newest value from the Array.

First, i want to store every value that is made in book() in global array and get every value in load() from getItem. How can i make that possible?

2

There are 2 best solutions below

0
On

To clarify. So I want my array (which is converted to a string) inserted into SetItem in sessionStorage to be stored each time I use book (). Then each string will be presented in getItem in load ().

1
On

The sessionStorage can persist only until the current session expires. Use localStorage instead.

Data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores.