Skip to content Skip to sidebar Skip to footer

Auto-save All Inputs Value To LocalStorage And Restore Them On Page Reload

I'm about to code, in Javascript some code (involving looping on each and adding listeners): allowing, after keypress, to save all values to localStora

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

Solution 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

Solution 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.


Post a Comment for "Auto-save All Inputs Value To LocalStorage And Restore Them On Page Reload"