I am trying to save the data into my object from input fileds using the localStorage but when I add a value into input and save it, it saves but when I try to add new value it deletes the old value and adds the new one instead. My demands are in the following :
localStorage. how can I do that ?here is the code : JavaScript:
let links = {
team1: {
icon: "FCL.png",
list: [{ name: "Real Madrid", url: "www.Real Madrid.com" }]
},
team2: {
icon: "FCL.png",
list: [{ name: "FC Barcelona", url: "www.FCB.com" }]
},
fav: {
icon: "fav.png",
list: []
}
};
$("#click").click(function () {
const link = document.querySelector("#link").value;
const name = document.querySelector("#name").value;
links["fav"].list.push({ url: link, name: name });
localStorage.setItem("links", JSON.stringify(links));
console.log(localStorage.setItem("links", JSON.stringify(links)));
});
HTML:
<form name="form1" action="">
<input type="text" name="link" id="link" />
<input type="text" name="name" id="name" />
<button id="click">click</button>
</form>
here sandbox : enter link description here
So, the problem is when you are reloading web page, the links variable is getting the initial value you declared in your code. If you want to keep persisting the updating links, you need to first check if links already exists in localStorage, if so, then assign it to linksor else set the default value.
Example:
const localStorageLinks = JSON.parse(localStorage.getItem("links"))
let links = localStorageLinks || {
team1: {
icon: "FCL.png",
list: [{ name: "Real Madrid", url: "www.Real Madrid.com" }]
},
team2: {
icon: "FCL.png",
list: [{ name: "FC barcelona", url: "www.FCL.com" }]
},
fav: {
icon: "fav.png",
list: []
}
};
Now, even if you reload the page your links will have the latest updated links.
setItem() method will add the key to the given LocalStorage object, or update (replace) that key's value if it already exists.
If
You have to use JSON.parse() method parses a JSON string in LocalStorage, add the new value.
list = JSON.parse(localStorage.getItem("links") || [];
list.push({ url: link, name: name });
localStorage.setItem("links", JSON.stringify(links));