Categories
JavaScript Answers

How to reload current page without losing any form data with JavaScript?

Spread the love

Sometimes, we want to reload current page without losing any form data with JavaScript.

In this article, we’ll look at how to reload current page without losing any form data with JavaScript.

How to reload current page without losing any form data with JavaScript?

To reload current page without losing any form data with JavaScript, we can save data to local storage and then get the values after the page reloads.

For instance, we write

window.onbeforeunload = () => {
  localStorage.setItem("name", document.querySelector("#inputName").value);
  localStorage.setItem("email", document.querySelector("#inputEmail").value);
  localStorage.setItem("phone", document.querySelector("#inputPhone").value);
  // ...
};

window.onload = () => {
  const name = localStorage.getItem("name");
  if (name !== null) {
  }

  // ...
};

to set window.onbeforeunload to a function that’s called before we unload the page.

We get the values from the inputs and save them to local storage with localStorage.setItem.

Then we set window.onload to a function that’s called when the page is loaded.

In it, we get the local storage entry with the key with getItem.

Conclusion

To reload current page without losing any form data with JavaScript, we can save data to local storage and then get the values after the page reloads.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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