Skip to content

Instantly share code, notes, and snippets.

@zzzzBov
Last active December 18, 2015 00:09
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 zzzzBov/5695035 to your computer and use it in GitHub Desktop.
Save zzzzBov/5695035 to your computer and use it in GitHub Desktop.
Flag unsaved changes when a user leaves a page with a saveable form
(function (root, $) {
"use strict";
$('[data-saveable]').on('change', ':input', function () {
//flag the form as having changed
$(this).closest('[data-saveable]').data('saveable', true);
}).on('submit', function (e) {
//if the form is successfully being submitted, it's probably being saved
if (!e.isDefaultPrevented()) {
//force the saveable input to lose focus
//to trigger any possible change events
$('[data-saveable] :input').blur();
//unflag the form, as it's being saved
$(this).data('saveable', false);
}
});
$(window).on('beforeunload', function () {
var unsavedChanges;
//force the saveable input to lose focus
//to trigger any possible change events
$('[data-saveable] :input').blur();
unsavedChanges = $('[data-saveable]').filter(function () {
return !!$(this).data('saveable');
}).length > 0;
if (unsavedChanges) {
return 'You have unsaved changes.';
}
});
}(this, this.jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment