Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

JavaScript code:

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

HTML code:

<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">
like image 468
michelle9090 Avatar asked Feb 03 '26 07:02

michelle9090


2 Answers

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));
}
like image 195
Algirdas Avatar answered Feb 05 '26 21:02

Algirdas


Get the data first, push the new value then overwrite it:

function reason(){
        var dropd = document.getElementById("savedrop").value;
        var drophistory = JSON.parse(localStorage.getItem("savedrop"));
        drophistory.push(droph);
        localStorage.setItem("reason", JSON.stringify(drophistory));
    }
like image 27
Bünyamin Sarıgül Avatar answered Feb 05 '26 20:02

Bünyamin Sarıgül



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!