Created
May 22, 2014 08:21
-
-
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
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
<form action="..." data-unsaved-warning> | |
<!-- Something something the form --> | |
</form> |
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
$(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