I need to detect unsaved data in form when user leaves the page without submitting the form. I would like to implement that without adding a value change listener to each in
This worked for me.
$(function() {
// Set the unload message whenever any input element get changed.
$('input').change(function() {
setConfirmUnload(true);
});
// Turn off the unload message whenever a form get submitted properly.
$('form').submit(function() {
setConfirmUnload(false);
});
});
function setConfirmUnload(on) {
var message = "You have unsaved data. Are you sure to leave the page?";
window.onbeforeunload = (on) ? function() { return message; } : null;
}