admin管理员组

文章数量:1399839

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?

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?

Share Improve this question asked Apr 7, 2020 at 16:48 BasjBasj 46.6k110 gold badges456 silver badges807 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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" />

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

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.

本文标签: javascriptAutosave all inputs value to localStorage and restore them on page reloadStack Overflow