Skip to content

Instantly share code, notes, and snippets.

@martinbean
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinbean/8d299655f4207c580cac to your computer and use it in GitHub Desktop.
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.
(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);
@martinbean
Copy link
Author

Example usage:

<form action="" method="POST" data-confirm-unload>
  <!-- inputs -->
</form>
<script>
  $('[data-confirm-unload]').confirmUnload();
</script>

You can also customise the message displayed in the dialog box:

$('[data-confirm-unload]').confirmUnload({
  message: 'Save you changes, foo’!'
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment