Auto-save all inputs value to localStorage and restore them on page reload

谁说胖子不能爱 提交于 2020-05-30 08:12:43

问题


I'm about to code, in Javascript some code (involving looping on each <input> and adding listeners):

  • allowing, after keypress, to save all <input> values to localStorage
  • restore all <input> values from localStorage in the case the page/browser has been closed and reopened on the same page

But maybe is there an automatic way, provided by the browsers?

e.g. by adding an attribute to <input>, similar to <input autofocus> (which is not related here)

Question: is there an autosave feature of <form> <input> HTML tags?


回答1:


As far as I know, there is no built-in way to do that, you should do it manually;

function persist(thisArg) {
  localStorage.setItem(thisArg.id, thisArg.value);
}
<input id="test" onchange="persist(this)" />

persist and retrieve all together:

function persist(event) {
  localStorage.setItem(event.target.id, event.target.value);
}

// you may use a more specific selector;
document.querySelectorAll("input").forEach((inputEl) => {
  inputEl.value = localStorage.getItem(inputEl.id);
  inputEl.addEventListener("change", persist);
});
<input id="test" />



回答2:


there is no automatic way to do that. you have two options :

  1. save the data by code
    example:
localStorage.setItem('testObject', JSON.stringify(yourObject)); // for storing data
JSON.parse(localStorage.getItem('yourObject')); // for retrieving data


code snippet:

// for saving data

function saveData(el) {
  localStorage.setItem(el.id, JSON.stringify(el.value));
}

// for retrieving data on page load

function getData() {
  var inp = document.getElementById("inp");
  inp.value = JSON.parse(localStorage.getItem('inp')) || "";
}
<body onload="getData()">
    <input id="inp" onchange="saveData(this)" />
</body>
  1. try a helper library like persisto



回答3:


Based on the accepted answer, here is a one-liner that can be useful:

document.querySelectorAll('input:not([type="submit"])').forEach(elt => { elt.value = localStorage.getItem(elt.name); elt.addEventListener("change", e => { localStorage.setItem(e.target.name, e.target.value); }); });

It serializes/deserializes the <input>s to localStorage, indexed by their attributes name.



来源:https://stackoverflow.com/questions/61085148/auto-save-all-inputs-value-to-localstorage-and-restore-them-on-page-reload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!