Skip to content

Instantly share code, notes, and snippets.

@tentacode
Created May 22, 2014 08:21
Show Gist options
  • Save tentacode/fc6a4646b9140e02dfdf to your computer and use it in GitHub Desktop.
Save tentacode/fc6a4646b9140e02dfdf to your computer and use it in GitHub Desktop.
Small jQuery script that notices the user when leaving the page without saving after updating a form
<form action="..." data-unsaved-warning>
<!-- Something something the form -->
</form>
$(document).ready(function() {
$('body').on(
'change',
'form[data-unsaved-warning] select, form[data-unsaved-warning] input, form[data-unsaved-warning] textarea',
function(e) {
$(e.target).parents('form').attr('data-unsaved-changes', '1');
}
);
$('body').on('submit', 'form[data-unsaved-warning]', function(e){
$(e.target).data('submitting', '1');
$(e.target).data('unsaved-changes', '0');
})
$(window).bind('beforeunload', function(e){
var error = '';
$('form[data-unsaved-changes="1"]').each(function(i, form) {
if ($(form).data('submitting') !== '1') {
error = "Warning : you did not save your form !";
}
})
if (error != '') {
return error;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment