Skip to content

Instantly share code, notes, and snippets.

@mikehins
Last active August 29, 2015 14:05
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 mikehins/7bf60df6d23402f33445 to your computer and use it in GitHub Desktop.
Save mikehins/7bf60df6d23402f33445 to your computer and use it in GitHub Desktop.
Alert user to save before unload
$(document).ready(function() {
// ----------------------------
// Show message if data have been modified without saving first
// ----------------------------
var CHANGED = false;
window.onbeforeunload = function() {
return (CHANGED == true ? "Leaving Page with unsaved changes" : null);
}
// ----------------------------
// Store initial input values in DOM data and listen for any changes to modify the CHANGED variable
// ----------------------------
$("input, select, textarea").each(function() {
$.data(this, "lastvalue", $(this).val());
$(this).bind("keyup keydown keypress change blur", function() {
CHANGED = $(this).val() !== $.data(this, "lastvalue") ? true : false;
});
});
// ----------------------------
// Deactivate the window onbeforeload event if the form is submitted
// ----------------------------
$('form').submit(function() {
CHANGED = false;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment