Alert for unsaved changes in form in JavaScript

Following is the code to display an alert for form’s unsaved changes in JavaScript −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   input {
      margin: 10px;
<body onbeforeunload="return pageUnload()">
<h1>Alert for unsaved changes in form</h1>
Username <input type="text" />
<br />
Password <input type="password" /><br />
<button type="submit">SUBMIT</button>
<br />
   function pageUnload() {
      return "The data on this page will be lost if you leave";


If we click on the reload button then the following warning will be shown −