michelle9090 michelle9090 - 5 days ago 6
HTML Question

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 just want to keep adding value to my localstorage without it overwriting. Any help will be appreciated, thanks.

js:

function reason(){
var dropd = document.getElementById("savedrop").value;
var drophistory = JSON.parse(localStorage.getItem("savedrop"));
localStorage.setItem("reason", JSON.stringify(dropd));
}


html:

<select id="savedrop">
<option value="" disabled="disabled" selected="selected">Please choose one</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<input id="btnbutton" class="btn" type="button" onClick="reason()" value="Submit">

Answer

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:

function reason(){
    var dropd = document.getElementById("savedrop").value;
    var drophistory = JSON.parse(localStorage.getItem("reason")) || [];
    drophistory.push(dropd);
    localStorage.setItem("reason", JSON.stringify(drophistory));
}
Comments