views:

286

answers:

3

Is it possible that the same name used can have many different values stored separately and to be shown in a list?

E.g.:

function save()
{
    var inputfield = document.getElementById('field').innerHTML;
    localStorage['justified'] = inputfield;
}

<input type="text" id="field" onclick="save();" />

Every time someone enters something in the input field, and click on save, the localstorage will only save the value in the same name, however, does this conflict the way storage are saved, like being replaced with the latest input value?

Also, is there any way to prevent clearing the localstorage when clearing the cache?

+1  A: 

This is something quite easily determined with a very simple test page. You can only store one value per key, and the values are not cleared when the cache is cleared. (I've just tried Firefox so far ...)

You can store a list of values in a single key by writing your own function to do it:

function addToPersistentList(listName, value) {
  var val = localStorage[listName] || [];
  val.push(value);
  localStorage[listName] = val; // THIS DOES NOT WORK
}

edit oops it only supports stored strings; crap. OK well if you have json2 you'd do this:

function addToPersistentList(listName, value) {
  var val = localStorage[listName] ? JSON.parse(localStorage[listName]) : [];
  val.push(value.toString());
  localStorage[listName] = JSON.stringify(val);
}

Of course this causes issues if you want to store dates etc.

Pointy
Tried Chrome, clearing cache doesnt clear data. But clearing cookies "..and other browser data" does clear it.
WmasterJ
A: 

No. You can store only one value in a localStorage entry.

There are two ways to store more values behind one keyword:

  1. Use localStorage['justified_0'], localStorage['justified_1'] etcetera.
  2. Store multiple values in an array and convert it to JSON before storing in localStorage['justified'] and convert it back to an array after reading.

Clearing the cache does not clear local storage.

edwin
+1  A: 

Actually localStorage 'should' be capable of storing integers, strings and arrays. I have been working on a notepad app using localStorage and save all my data using object literals:

var someData = {
    withvars: "and values",
    init: funtion() {
        // not sure if this works but it should.
    },
    var1: {
        subvar1: "data",
        subvar2: "data2"
    }
};

Then store it using JSON.stringify():

localStorage.setItem(varName, JSON.stringify(someData));

Then access it later with JSON.parse():

var dataBack = JSON.parse(localStorage.getItem("varName"));

If you always use object literals then you will have less trouble keeping track of how to store and how to retrieve data from localStorage.

WmasterJ