cheesycoder
cheesycoder

Reputation: 93

Save more than one user input into local storage

I was wondering if someone could help me with local storage. I want to be able to store more than one user value into local storage and display them all individually so they can be used as buttons/links. Below there is some code that I've tried:

    locatArray = new Array();

    function save() {
        var fieldValue = document.getElementById("input").value;
        var locatItem = locatArray.push(fieldValue);

        localStorage.setItem("text", JSON.stringify(locatArray));
    }

    window.onload = function load() {
        var storedValue = JSON.parse(localStorage.getItem("text"));
        if(storedValue) {
            document.getElementById("display").innerHTML = (storedValue);
        }

This code allows a user to store more than one value in a key. However, as it is an array, when the page is refreshed and the user enters different data, the local storage values are overwritten. Also each value cannot be accessed individually.

I'm new to using local storage and I was wondering if someone could help me out.

Upvotes: 1

Views: 1543

Answers (1)

Mior
Mior

Reputation: 831

You need to update your data not override it. Implement some synchronization mechanism that will first get data from localStorage and just push new item and store it again updated not override stored data.

If you want to remove some item do same thing. Get array from localStorage and just remove item you don't want anymore and store array in localStorage again.

using your code: weather_urls as key.

This will update your array stored in localStorage

function save() {
    var fieldValue = document.getElementById("input").value;

    var arrayOfLinks = localStorage.getItem("weather_urls");
    if(!arrayOfLinks){
        arrayOfLinks = []; // this is better way how to declare array not new Array()
    }
    arrayOfLinks.push(fieldValue);
    localStorage.setItem("weather_urls", arrayOfLinks);
}

window.onload = function load() {
    var storedValue = localStorage.getItem("weather_urls");
    if(storedValue) {
        document.getElementById("display").innerHTML = storedValue;
    }

Upvotes: 1

Related Questions