Localstorage Keeps Overwriting My Data
I am saving values from my dropdown box into localStorage. However, I don't want the data to be overwritten with the new info the next time user choose from the dropdown menu. I ju
Solution 1:
In localStorage
data is saved in key value pairs of strings.
Each time you call setItem()
it will add or overwrite existing value. And getItem()
just fetches the value stored in localStorage
which is a string value. To solve this you have to use an array, stringify
it and then store it.
Below is the correct code:
functionreason(){
var dropd = document.getElementById("savedrop").value;
var drophistory = JSON.parse(localStorage.getItem("reason")) || [];
drophistory.push(dropd);
localStorage.setItem("reason", JSON.stringify(drophistory));
}
Solution 2:
Get the data first, push the new value then overwrite it:
functionreason(){
var dropd = document.getElementById("savedrop").value;
var drophistory = JSON.parse(localStorage.getItem("savedrop"));
drophistory.push(droph);
localStorage.setItem("reason", JSON.stringify(drophistory));
}
Post a Comment for "Localstorage Keeps Overwriting My Data"