michelle9090 michelle9090 - 1 year ago 69
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.


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


<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>
<input id="btnbutton" class="btn" type="button" onClick="reason()" value="Submit">

Answer Source

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")) || [];
    localStorage.setItem("reason", JSON.stringify(drophistory));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download