2

I am trying to store the specSize, specTitle and specURL which are in table to session storage, will be using it in different page. On load I see the session data, but if i try to add the items to session storage by clicking the button it clears the existing items and put the new ones instead of appending the onclick items to existing ones.

Here is my code:

 window.specSize;
 window.specTitle;
 window.specURL;

 function specInfo (sSize, sTitle, sURL){
  this.specSize = sSize;
  this.specTitle = sTitle;
  this.specURL = sURL;
 }
 var specArr = []
 $('.flag-bookmarks a').on("click",function(e){
    e.preventDefault();
    specSize = $(this).parent().parent().parent().find("td:first").html();
    specTitle = $(this).parent().parent().parent().find("td:nth-child(2) a").html();
    specURL=$(this).parent().parent().parent().find("td:nth-child(2) a").attr("href");
    specArr.push(new specInfo(specSize,specTitle,specURL))
    sessionStorage.setItem('storedInfo', JSON.stringify(specArr));
 });
  storedValue = JSON.parse(sessionStorage.getItem('storedInfo'));
  alert(storedValue);
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
user3205881
  • 71
  • 1
  • 6

1 Answers1

2

The problem is session storage only supports data type as "String" for storing. So you need to JSON.stringify your object before setting and JSON.parse it for getting the session storage object.

Reference: How do I store an array in localStorage?

So you have to do the following

  1. Get the items from session storage in a variable using JSON.parse(sessionStorage.getItem('storedInfo'));
  2. Append the new items to the above variable
  3. Set the session storage using JSON.stringify();

Since you're already stringifying before setting, you have to do the first and second step.

Hope this helps

Community
  • 1
  • 1
Gopinath Shiva
  • 3,822
  • 5
  • 25
  • 48