ArticleZip > Alert For Unsaved Changes In Form

Alert For Unsaved Changes In Form

Imagine you have filled out a lengthy form on a website, and just as you're about to submit it, disaster strikes - your browser crashes or you accidentally close the tab. Fret not, for there's a simple solution to avoid losing all your hard work. In this article, we'll guide you through adding an alert for unsaved changes in a form using JavaScript.

To implement an alert for unsaved changes, we'll leverage the `beforeunload` event in JavaScript. This event is triggered just before the window is unloaded, allowing us to intervene whenever a user tries to navigate away from the page without saving their form data.

First things first, let's create a basic form in HTML that we can work with:

Html

<!-- Your form fields here -->
    
    
    <!-- more fields as needed -->

Next, we'll write the JavaScript to detect changes in the form and display a confirmation message if the user attempts to leave the page without saving:

Javascript

let formChanged = false;

document.getElementById("myForm").addEventListener("change", function() {
    formChanged = true;
});

window.addEventListener("beforeunload", function(e) {
    if (formChanged) {
        e.preventDefault();
        e.returnValue = ''; // This is to display a generic message in older browsers
        return 'You have unsaved changes. Are you sure you want to leave?';
    }
});

// You can also add additional logic to handle saving the form data before unloading the page

In the code snippet above, we start by setting a variable `formChanged` to `false`. Whenever a change event is detected within the form fields, we update `formChanged` to `true`, indicating that there are unsaved changes.

The `beforeunload` event listener is where the magic happens. If `formChanged` is `true` when the user tries to leave the page, we prevent the default behavior, set a generic message (for older browsers), and return a custom confirmation message to prompt the user to stay on the page and save their changes.

You can also extend this functionality by adding logic to save the form data before allowing the user to navigate away, ensuring that no data is lost in the process.

By incorporating this simple yet effective alert for unsaved changes in your form, you provide users with an added layer of protection against accidental data loss, improving the overall user experience on your website. Happy coding!