Last active
August 29, 2015 14:20
-
-
Save martinbean/8d299655f4207c580cac to your computer and use it in GitHub Desktop.
Displays a confirmation dialog if a form’s changed and the user tries to leave the page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
$.fn.confirmUnload = function (options) { | |
var settings = $.extend({ | |
message: 'You have unsaved changes.' | |
}, options); | |
return this.filter('form').each(function () { | |
var form = $(this); | |
var dataOnLoad = form.serialize(); | |
form.find('input').on('change keyup', function (e) { | |
var currentData = form.serialize(); | |
if (currentData != dataOnLoad) { | |
window.onbeforeunload = function () { | |
return settings.message; | |
}; | |
} else { | |
window.onbeforeunload = null; | |
} | |
}); | |
form.submit(function (e) { | |
window.onbeforeunload = null; | |
}); | |
}); | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
You can also customise the message displayed in the dialog box: