I have a number coming from an <input>
, that I would like to save in an array in a chosen place. I succeeded in doing it with splice()
, but the data saved in array resets when the page is reloaded. How can I save that data "forever" ?
This is the code:
<label for="number">Number to Save</label>
<input type="text" name="number" id="number" value=""/>
<input type="button" value="click" onclick="myArr.splice(2, 0, number.value);"/>
Here is simple sample of using localStorage http://jsfiddle.net/7e2o6ptw/
// Retrieve your data from locaStorage
const saveData = JSON.parse(localStorage.getItem("saveData") || null) || {};
// Store your data.
function saveStuff(obj) {
saveData.obj = obj;
const myArr = [1,2,3,4,5];
console.log(myArr);
saveData.some_array = myArr;
console.log(saveData.some_array);
saveData.some_array = myArr.splice(2);
localStorage.setItem("saveData", JSON.stringify(saveData));
}
// Do something with your data.
function loadStuff() {
return saveData.obj || "default";
}
if (saveData.some_array) alert("You were here: " + saveData.some_array);
saveStuff("Stuff");
You can not store data forever. But you can store them in a cookie.
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
Read more about JS cookies :- https://www.w3schools.com/js/js_cookies.asp
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.