Hello, web developers, In this article! we'll see how to display unsaved changes browser warning modal using jQuery. Here, we'll see how to display an alert user before leaving the web page with unsaved changes on the form using JavaScript.
We'll use beforeunload javascript method. The beforeunload
event is fired when the current window, contained document, and associated resources are about to be unloaded.
Alert user before leaving web page with unsaved changes on form javascript
The main use case for this event is to trigger a browser-generated confirmation dialog that asks users to confirm if they really want to leave the page when they try to close or reload it, or navigate somewhere else. This is intended to help prevent the loss of unsaved data.
Syntax:
addEventListener("beforeunload", (event) => {});
onbeforeunload = (event) => {};
Example:
In this example, we'll add HTML input to represent some data that could be changed and require saving.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How to Display Unsaved Changes Browser Warning - Techsolutionstuff</title>
</head>
<body>
<form>
<input type="text" name="name" id="name" />
</form>
<script>
const beforeUnloadHandler = (event) => {
event.preventDefault();
// Included for legacy support, e.g. Chrome/Edge < 119
event.returnValue = true;
};
const nameInput = document.querySelector("#name");
nameInput.addEventListener("input", (event) => {
if (event.target.value !== "") {
window.addEventListener("beforeunload", beforeUnloadHandler);
} else {
window.removeEventListener("beforeunload", beforeUnloadHandler);
}
});
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>How to Display Unsaved Changes Browser Warning using jQuery - Techsolutionstuff</title>
</head>
<body>
<form class="article-form">
<input type="text" name="name" id="name" />
<select name="country">
<option value="1">USA</option>
<option value="2" selected>India</option>
<option value="3">UK</option>
</select>
<textarea name="description">This is text area</textarea>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
$(document).ready(function() {
var formChanged = false;
$('.article-form input, .article-form select, .article-form textarea').on('input change', function() {
formChanged = true;
});
$('.article-form').submit(function() {
formChanged = false;
});
$(window).on('beforeunload', function() {
if (formChanged) {
return 'Changes you made may not be saved.';
}
});
});
</script>
</body>
</html>
You might also like: