Reputation: 310
I want to save the value of user input into the local storage, which will I hope to stay even after the page refreshes or I close the browser completely. How do I do this?
allNames = []
function submit() {
var names = document.getElementById("names").value;
allNames.push(names);
localStorage.setItem("names", names)
}
document.getElementById("namesList").innerHTML = allNames
<input id="names" placeholder="Enter Your Party's names">
<button onclick="submit()">Submit</button>
<div id="namesList"></div>
I would like for the total names to be saved and displayed into the tag even after the page refreshes. How do I do this?
Upvotes: 1
Views: 3233
Reputation: 5542
You can use window.localStorage
, it persists after browser reload.
Set data:
localStorage.setItem('test', 'value');
Get data:
localStorage.getItem('test');
Remove data:
localStorage.removeItem('test');
First, you need to load the data to namesList
from localStorage
, then on submit just push to the previously saved data, and save it again, load the new data.
Also, in order to work as expected, you need to use JSON.stringify
before saving it to the localStorage
, and JSON.parse
after you get the data.
With your code, working example on jsBin:
function submit() {
var names = document.getElementById("names").value;
var allNames = JSON.parse(localStorage.getItem("allNames")) || [];
allNames.push(names);
localStorage.setItem("allNames", JSON.stringify(allNames));
document.getElementById("names").value = '';
document.getElementById("namesList").innerHTML = localStorage.getItem("allNames");
}
document.getElementById("namesList").innerHTML = localStorage.getItem("allNames");
<input id="names" placeholder="Enter Your Party's names">
<button onclick="submit()">Submit</button>
<div id="namesList"></div>
Upvotes: 2
Reputation: 10204
You can do like this.
allNames = localStorage.getItem("names");
if (allNames) allNames = allNames.split(';;;');
document.getElementById("namesList").innerHTML = allNames
function submit() {
var partnerName = document.getElementById("names").value;
allNames.push(names);
localStorage.setItem("namesList", allNames.join(';;;'));
document.getElementById("namesList").innerHTML = allNames;
}
Upvotes: 1
Reputation: 1055
You can try this
// Store data
var someData = 'The data that I want to store for later.';
localStorage.setItem('myDataKey', someData);
// Get data
var data = localStorage.getItem('myDataKey');
// Remove data
localStorage.removeItem('myDatakey');
DOC
https://developer.mozilla.org/pt-BR/docs/Web/API/Storage/setItem
Upvotes: 0