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

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.