Skip to content

Instantly share code, notes, and snippets.

@jordanbyron
Created September 27, 2011 12:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanbyron/1244892 to your computer and use it in GitHub Desktop.
Save jordanbyron/1244892 to your computer and use it in GitHub Desktop.
Simple Save Changes Checker
/*
* save.js
* Track changes in a form and display a warning if they haven't been submitted
*
* Usage:
* Add 'data-track-changes=true' to any form which you want to track changes
*
* <form data-track-changes=true> ... </form>
*/
Save = {
init: function(){
// Track keydown so changes are tracked immediately in
// textarea and input[type=text] elements, and change for select
jQuery('form[data-track-changes=true] :input').
keydown(Save.change).change(Save.change);
jQuery('form[data-track-changes=true]').submit(function(e){
jQuery('*[data-changed=true]').attr('data-changed', false);
});
jQuery(window).bind('beforeunload', Save.beforeUnload);
},
beforeUnload: function(){
if(Save.changesMade()) return "You have unsaved changes.";
},
changesMade: function(){
return (jQuery('*[data-changed=true]').length > 0)
},
change: function(){
jQuery(this).attr('data-changed', true);
}
};
jQuery(function() { Save.init(); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment