Categories
JavaScript Answers

How to Alert for Unsaved Changes in Form with JavaScript?

Spread the love

Sometimes, we want to alert for unsaved changes in form with JavaScript.

In this article, we’ll look at how to alert for unsaved changes in form with JavaScript.

Alert for Unsaved Changes in Form with JavaScript

To alert for unsaved changes in form with JavaScript, we can track changes done to inputs in a form.

Then we can set the window.onbeforeunload property to a function that checks the changing state of the input and returns an alert message if there’re changes.

For instance, if we have:

<div id="app">
  <input />
</div>

Then we can write the following JavaScript to track whether the input value has changed and shows the alert when the user leaves the page when there’re changes made:

let unsaved = false;

const input = document.querySelector("input");
input.addEventListener("change", () => {
  unsaved = true;
});

const unloadPage = () => {
  if (unsaved) {
    return "You have unsaved changes on this page.";
  }
};

window.onbeforeunload = unloadPage;

We have the unsaved variable, which we set to true in the change event listener of the input that we added with input.addEventListener .

And then we have the unloadPage function that checks if unsaved is true .

If it is, then we return a string that triggers the alert when we set the function as the value of window.onbeforeunload .

The message can’t be changed, so we can return any string.

onbeforeunload runs when we leave the page.

Conclusion

To alert for unsaved changes in form with JavaScript, we can track changes done to inputs in a form.

Then we can set the window.onbeforeunload property to a function that checks the changing state of the input and returns an alert message if there’re changes.

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 *