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;

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

persist and retrieve all together:

functionpersist(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);
});
<inputid="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 dataJSON.parse(localStorage.getItem('yourObject')); // for retrieving data

code snippet:

// for saving datafunctionsaveData(el) {
  localStorage.setItem(el.id, JSON.stringify(el.value));
}

// for retrieving data on page loadfunctiongetData() {
  var inp = document.getElementById("inp");
  inp.value = JSON.parse(localStorage.getItem('inp')) || "";
}
<bodyonload="getData()"><inputid="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"