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?
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".
It is not a good solution but it works and is performative.
localStorage.setItem("fruit", "Apples");
localStorage.setItem("fruit", localStorage.getItem("fruit") + "Orange");
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With