Last active
August 29, 2015 14:05
-
-
Save mikehins/7bf60df6d23402f33445 to your computer and use it in GitHub Desktop.
Alert user to save before unload
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() { | |
// ---------------------------- | |
// 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