Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append to HTML5 localStorage?

I do a

localStorage.setItem('oldData', $i("textbox").value);

to set the value of key oldData to the value in a textbox.

The next time something is entered to the textbox, I want to append to the already existing oldData.

So, if I enter apples and then oranges in my textbox, my localStorage key oldData should look like this:

Initially:

Key      |   Value
---------------------------
oldData  |  apples

Now:

oldData  |  apples oranges

How can I append? Is there an append method provided?

Or do I need to read the data first, append in javascript and then write back?

like image 618
Lazer Avatar asked Oct 06 '11 20:10

Lazer


3 Answers

There's no append function. It's not hard to write one though:

function appendToStorage(name, data){
    var old = localStorage.getItem(name);
    if(old === null) old = "";
    localStorage.setItem(name, old + data);
}

appendToStorage('oldData', $i("textbox").value);

Note: It makes more sense to define a function append on the localStorage object. However, because localStorage has a setter, this is not possible. If you were trying to define a function using localStorage.append = ..., the localStorage object will interpret this attempt as "Save an object called append in the Storage object".

like image 143
Rob W Avatar answered Oct 20 '22 07:10

Rob W


It is not a good solution but it works and is performative.

localStorage.setItem("fruit", "Apples"); 

localStorage.setItem("fruit", localStorage.getItem("fruit") + "Orange");
like image 43
Nery Jr Avatar answered Oct 20 '22 09:10

Nery Jr


I found this here :

interface Storage {
  readonly attribute unsigned long length;
  DOMString? key(unsigned long index);
  getter DOMString getItem(DOMString key);
  setter creator void setItem(DOMString key, DOMString value);
  deleter void removeItem(DOMString key);
  void clear();
};

Seems like it only has getItem,setItem,removeItem,clear,key and length.

like image 2
XCS Avatar answered Oct 20 '22 07:10

XCS