1

Есть форма регистрации. Поля Name, E-mail, Date of Birth сохраняются в localStorage.

Как правильно прописать функцию, которая проверяет, есть ли заданные значения у соответствующих ключей в localStorage, и если есть, складывает значения в соответствующие поля при перезагрузке страницы?

Для одного поля понятно, как это сделать. А для трех не совсем. Прописывать кучу IF не хочется.

window.onload = function () {

    //Set localStorage

    var userName = document.getElementById("nameField");
    var userEmail = document.getElementById("emailField");
    var userDateOfBirth = document.getElementById("dateField");


    //Wnen out of focus - set localStorage

    userName.addEventListener("focusout", (event) => {
        localStorage.setItem("userName", userName.value);
    });

     userEmail.addEventListener("focusout", (event) => {
         localStorage.setItem("userEmail", userEmail.value);
     });

      userDateOfBirth.addEventListener("focusout", (event) => {
          localStorage.setItem("userDateOfBirth", userDateOfBirth.value);
      });

    //Get localStorage

    var userNameStorage = localStorage.getItem("userName");
    var userEmailStorage = localStorage.getItem("userEmail");
    var userDateOfBirthStorage = localStorage.getItem("userDateOfBirth");

    function getLocalStorage() {

    }

    getLocalStorage();

};

JS FIDDLE

2 ответа 2

3

//Set localStorage

const userName = document.getElementById("nameField");
const userEmail = document.getElementById("emailField");
const userDateOfBirth = document.getElementById("dateField");


//Wnen out of focus - set localStorage

userName.addEventListener("focusout", (event) => {
  localStorage.setItem(event.target.id, userName.value);
});

userEmail.addEventListener("focusout", (event) => {
  localStorage.setItem(event.target.id, userEmail.value);
});

userDateOfBirth.addEventListener("focusout", (event) => {
  localStorage.setItem(event.target.id, userDateOfBirth.value);
});

//Get localStorage

function getLocalStorage() {
  const inputs = Array.from(document.querySelectorAll('input'));

  inputs.map(input => {
    const val = localStorage.getItem(input.id);
    return val ? input.value = val : input.value = '';
  })
}

getLocalStorage();
<section class="contactForm">
  <h1>Create account</h1>
  <form id="registration-form" action="php/register.php" method="POST">
    <p>
      <label>Your name</label>
      <input required type="text" name="name" value="" id="nameField">

    </p>
    <p>
      <label>Email</label>
      <input required type="email" name="email" value="" id="emailField">


    </p>
    <p>
      <label>Date of birth</label>
      <input required type="text" name="date" value="" id="dateField" class="datePicker">

    </p>
    <p>
      <label>Password</label>
      <input required type="password" name="password" value="" id="passwordField">

    </p>
    <p>
      <label>Re-enter Password</label>
      <input required type="password" name="re-password" value="" id="re-passwordField">

    </p>
    <p>
      <button class="full submitButton" type="submit">Create your account</button>
    </p>
  </form>

</section>

1

Проще и удобнее - примерно так:

const frm = document.querySelector('#registration-form'); 

// чтение
let state = JSON.parse(localStorage.getItem('regForm') || '{}'); 
Object.keys(state).forEach(name => {
  const inp = frm.querySelector(`[name="${name}"]`); 
  if (inp) inp.value = state[name]; 
}); 

/* ... */

// запись 
state = [...frm.querySelectorAll('input[name]')].reduce(
  (r, { name, value }) => Object.assign(r, { [name]: value })
, {}); 
localStorage.setItem('regForm', JSON.stringify(state)); 

Фильтрацию элементов (исходя из их name, type, или других атрибутов) - добавить по вкусу.

1
  • Спасибо. Интересный подход 7 ноя 2019 в 11:13

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.