Alert for unsaved changes in form in JavaScript

Preventing data loss is crucial in web forms. JavaScript's beforeunload event allows you to warn users when they attempt to leave a page with unsaved changes.

Basic Implementation

The simplest approach uses the beforeunload event to show a browser confirmation dialog:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Form Unsaved Changes Alert</title>
   <style>
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
         padding: 20px;
      }
      input {
         margin: 10px 0;
         padding: 8px;
         width: 200px;
      }
      button {
         padding: 10px 20px;
         margin: 10px 0;
      }
   </style>
</head>
<body>
   <h1>Form with Unsaved Changes Alert</h1>
   <form id="userForm">
      <div>
         Username: <input type="text" id="username" placeholder="Enter username">
      </div>
      <div>
         Email: <input type="email" id="email" placeholder="Enter email">
      </div>
      <div>
         <button type="submit">Submit</button>
         <button type="button" onclick="clearForm()">Clear</button>
      </div>
   </form>

   <script>
      let hasUnsavedChanges = false;

      // Track form changes
      document.getElementById('userForm').addEventListener('input', function() {
         hasUnsavedChanges = true;
      });

      // Show warning only if there are unsaved changes
      window.addEventListener('beforeunload', function(event) {
         if (hasUnsavedChanges) {
            event.preventDefault();
            return "You have unsaved changes. Are you sure you want to leave?";
         }
      });

      // Clear unsaved changes flag on form submission
      document.getElementById('userForm').addEventListener('submit', function() {
         hasUnsavedChanges = false;
      });

      function clearForm() {
         document.getElementById('userForm').reset();
         hasUnsavedChanges = false;
      }
   </script>
</body>
</html>

Smart Detection Method

A better approach only shows the warning when actual changes are detected:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Smart Unsaved Changes Detection</title>
   <style>
      body { font-family: Arial, sans-serif; padding: 20px; }
      .form-group { margin: 15px 0; }
      input, textarea { padding: 8px; margin-left: 10px; }
      button { padding: 10px 15px; margin: 5px; }
   </style>
</head>
<body>
   <h2>Contact Form with Smart Change Detection</h2>
   <form id="contactForm">
      <div class="form-group">
         Name: <input type="text" name="name" id="name">
      </div>
      <div class="form-group">
         Message: <textarea name="message" id="message" rows="4" cols="30"></textarea>
      </div>
      <div>
         <button type="submit">Save</button>
         <button type="button" id="discardBtn">Discard Changes</button>
      </div>
   </form>

   <script>
      let originalFormData = {};
      let formChanged = false;

      // Store original form values
      function storeOriginalData() {
         const form = document.getElementById('contactForm');
         const formData = new FormData(form);
         originalFormData = Object.fromEntries(formData.entries());
      }

      // Check if form has changed
      function checkFormChanges() {
         const form = document.getElementById('contactForm');
         const currentData = new FormData(form);
         const currentObj = Object.fromEntries(currentData.entries());
         
         formChanged = JSON.stringify(originalFormData) !== JSON.stringify(currentObj);
         return formChanged;
      }

      // Initialize original data when page loads
      window.addEventListener('load', storeOriginalData);

      // Monitor form changes
      document.getElementById('contactForm').addEventListener('input', checkFormChanges);

      // Beforeunload warning
      window.addEventListener('beforeunload', function(event) {
         if (checkFormChanges()) {
            event.preventDefault();
            return "Changes you made may not be saved.";
         }
      });

      // Handle form submission
      document.getElementById('contactForm').addEventListener('submit', function(event) {
         event.preventDefault();
         alert('Form saved successfully!');
         storeOriginalData(); // Update original data after save
         formChanged = false;
      });

      // Discard changes
      document.getElementById('discardBtn').addEventListener('click', function() {
         if (checkFormChanges()) {
            if (confirm('Are you sure you want to discard all changes?')) {
               location.reload();
            }
         } else {
            alert('No changes to discard.');
         }
      });
   </script>
</body>
</html>

How It Works

The beforeunload event fires when the user tries to:

  • Close the browser tab
  • Navigate to another page
  • Refresh the page
  • Close the browser window

The smart detection method compares current form values with the original values to determine if changes actually occurred.

Key Points

  • Modern browsers ignore custom messages in beforeunload and show their own standard dialog
  • The warning only appears when you return a truthy value or call event.preventDefault()
  • Always clear the warning flag after successful form submission
  • Use input event to detect changes across all form elements

Conclusion

Implementing unsaved changes alerts improves user experience by preventing accidental data loss. Use smart change detection to show warnings only when necessary, enhancing both functionality and user satisfaction.

Updated on: 2026-03-15T23:18:59+05:30

799 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements