Skip to content
Related Articles

Related Articles

Improve Article

How to display warning before leaving the web page with unsaved changes using JavaScript ?

  • Last Updated : 23 Nov, 2020

The onbeforeunload event handler is used for processing beforeunload events. This event is fired whenever a window is about to unload its resources. The result of this event depends on the user selection to proceed or cancel the action. This event can be used to check whether the user has left a form incomplete or unsaved by following this approach. 

Every form field on the page is used to update their respective variable by calling a function. These variables are checked whenever beforeunload is fired, thereby checking if the user is trying to leave the page without saving changes. It would not alert the user if the form is empty as the user has not started filling the form.

Syntax:

// Event listener for the 'beforeunload' event
window.addEventListener('beforeunload', function (e) {

    // Check if any of the input fields are filled
    if (fname !== '' || lname !== '' || subject !== '') {

        // Cancel the event and show alert that
        // the unsaved changes would be lost
        e.preventDefault();
        e.returnValue = '';
    }
});

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        .container {
            border: 2px dotted;
            width: 60%;
            border-radius: 5px;
            padding: 10px;
        }
  
        input,
        textarea {
            width: 90%;
            padding: 10px;
            margin: 10px;
        }
  
        .submit-btn {
            background-color: green;
            color: white;
            padding: 10px;
        }
    </style>
</head>
  
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
  
    <p>
        The page will notify if the user has
        started filling the form and tries
        to navigate away from it.
    </p>
  
    <div class="container">
        <h2>A Demo Contact Form</h2>
        <form action="#">
            <label>First Name</label>
  
            <!-- Create all the input boxes and
            assign there respective functions
            to update the content in a variable -->
            <input type="text" id="fname" 
                name="firstname" 
                onchange="updateFname()">
  
            <label>Last Name</label>
            <input type="text" id="lname" 
                name="lastname" 
                onchange="updateLname()">
  
            <label>Subject</label>
            <textarea id="subject" name="subject" 
                style="height:100px" 
                onchange="updateSubject()">
        </textarea>
  
            <button class="submit-btn" 
                onclick="return false;">
                Submit
            </button>
        </form>
    </div>
  
    <script type="text/javascript">
  
        // Variables to store the input text
        let fname = '';
        let lname = '';
        let subject = '';
  
        // Functions to update the input text
        updateFname = () => {
            fname = document
                .getElementById('fname').value;
        }
  
        updateLname = () => {
            lname = document
                .getElementById('lname').value;
        }
  
        updateSubject = () => {
            subject = document
                .getElementById('subject').value;
        }
  
        // Event listener for the 
        // 'beforeunload' event
        window.addEventListener('beforeunload', 
                                function (e) {
  
            // Check if any of the input
            // fields are filled
            if (fname !== '' ||
                lname !== '' ||
                subject !== '') {
  
                // Cancel the event and
                // show alert that the unsaved
                // changes would be lost
                e.preventDefault();
                e.returnValue = '';
            }
        });
    </script>
</body>
  
</html>

Output:

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :