简体   繁体   中英

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">

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));
}

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));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM