Form data not saved in localstorage except I refresh the browser

I am working on a form. The aim is to save the form data to … Read more Form data not saved in localstorage except I refresh the browser

I am working on a form. The aim is to save the form data to localStorage, and also populate the form fields with the data in the localStorage.

After submitting the form, data do not save to localStorage except I refresh the browser.

Even after I refresh and I see the data in localStorage, I open a new browser, launch the form. I check the localStorage but, the data do not show.

I will appreciate your advice.

Thank you

After submitting the form
enter image description here

After reloading the page
enter image description here

HTML Code

<form action="https://formspree.io/f/xwkaygyj" method="POST">
       <div class="name">
         <input id="name" type="text" name="name" required        placeholder="Name" oninput="onChangeHandler(this)"/>
       <input id="email" type="email" name="email" required placeholder="[email protected]" oninput="onChangeHandler(this)"/>
      <textarea id="message" name="message" cols="30" rows="7" maxlength="500" placeholder="Write your message here" required oninput="onChangeHandler(this)">
       </textarea>
                
     <button type="submit">Send</button>
   </div>
</form>

Javascript Code

const formName = document.getElementById('name');
const email = document.getElementById('email');
const message = document.getElementById('message');


let formData = { name: '', email: '', message: '' };

const onChangeHandler = (event) => {
  switch (event.name) {
    case 'name':
      formData = { ...formData, name: event.value };
      break;
    case 'email':
      formData = { ...formData, email: event.value };
      break;
    case 'message':
      formData = { ...formData, message: event.value };
      break;
    default:
      break;
  }
  localStorage.setItem('data', JSON.stringify(formData));
};
const reloadBrowser = JSON.parse(localStorage.getItem('data'));
if (reloadBrowser) {
  formName.value = reloadBrowser.name;
  email.value = reloadBrowser.email;
  message.value = reloadBrowser.message;
}

Source: JavaSript – Stack Overflow


Categories: NewsTags: ,

Tags: ,


Leave a Reply

Your email address will not be published. Required fields are marked *