Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple storages using localStorage

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?

like image 299
BonjourHolaOla Avatar asked Dec 28 '22 17:12

BonjourHolaOla


1 Answers

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: function() {
        // 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.

like image 71
JeroenEijkhof Avatar answered Dec 31 '22 06:12

JeroenEijkhof