Alert for unsaved changes in form in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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

Example

 Live Demo

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

Output

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

raja
Published on 18-Jul-2020 07:12:00
Advertisements