简体   繁体   中英

Pre-fill form with local storage

I'm loading questions from a JSON into my EJS template and want to populate each field from localStorage. The following saves the last value of each dropdown, text, and slider element:

var select = document.getElementsByTagName('select');
for (var i = 0; i < select.length; i++){
    select[i].value = localStorage.getItem(i);
}
jQuery("select").change(function () {
    for (var i = 0; i < select.length; i++){
        localStorage.setItem(i, select[i].value);
    }
});

I repeat this for all "input" tags. The issue is that the select values also get passed into text and slider — and vice versa (ie if I enter values for text and slider , they overwrite the select values, except they are left blank).

My end goal is to save each form-fields' most recent value so that my entries are not lost when I refresh the page.

It would be a lot more elegant to create a single localStorage entry representing your saved values, rather than pollute LS with many entries for each field. I would recommend something like this:

function save() {
  const selects = document.querySelectorAll('select');
  // select other element types
  // ...
  const selectValues = [...selects].map(select => select.value);
  const textValues = [...textInputs].map(textInput => textInput.value);
  const sliderValues = [...sliderInputs].map(sliderInput => sliderInput.value);
  const savedObj = { selectValues, textValues, sliderValues };
  localStorage.savedFormValues = JSON.stringify(savedObj);
}

That way, you only create a single entry in localStorage, and each entry type is quite distinct. Then, to get the values, just do the same thing in reverse:

function populate() {
  const selects = document.querySelectorAll('select');
  // ...
  const { selectValues, textValues, sliderValues } = JSON.parse(localStorage.savedFormValues);
  selectValues.forEach((selectValue, i) => selects[i].value = selectValue);
  // ...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM