0

I have an application where I am using JavaScript on the client-side to build a collection. On page1.html I have the following:

var collection = []; 
$.each(item, function (i, r) {
  collection.push(r);
});
alert(collection.length);

window.localStorage.setItem("collection", collection);

When this code executes, I see "4" in a message box. This is exactly what I am expecting. When I navigate to page2.html, I have the following:

$(document).ready(function () {
  var collection = window.localStorage.getItem("collection");
  alert(collection.length);
});

When this code executes, I see "63" in a message box. I was expecting "4". I have no idea what would cause this. My hunch is that it has something to do with the fact that I'm trying to store a collection and I'm not getting/setting like I should. This approach has worked for some purely string related values in my application. I'm not sure why its not working here though. Can anybody point me in the right direction?

Thanks!

JQuery Mobile
  • 6,221
  • 24
  • 81
  • 134

1 Answers1

0

localStorage can only be used to store objects as strings, so you'll need to serialize your list as a string (perhaps using commas or a null character).

One idea is to use jQuery's JSON.stringify method on collection and store that.

Feel free to check out this post for more information.

Community
  • 1
  • 1
Mike Christensen
  • 88,082
  • 50
  • 208
  • 326