Last active
December 18, 2015 00:09
-
-
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
This file contains hidden or 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 (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