Created
September 27, 2011 12:00
-
-
Save jordanbyron/1244892 to your computer and use it in GitHub Desktop.
Simple Save Changes Checker
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
/* | |
* 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