Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

To display a warning before leaving a web page with unsaved changes, you can use the beforeunload event in JavaScript.

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 = '';
}
});

Approach

  • 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’s 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 its 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.

Example: This example displays a warning before leaving the web page with unsaved changes using JavaScript.

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 = '';
        }
    });


HTML




<!DOCTYPE html>
<html>
<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 their 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>
</body>
</html>


CSS




.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;
}


Output: Click here to check the live output.



Last Updated : 16 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads