Last active
October 7, 2015 14:57
-
-
Save tzengerink/3182204 to your computer and use it in GitHub Desktop.
JavaScript Edit Protection
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
/*! | |
* EditProtection.js | |
* ----------------- | |
* | |
* Small module that provides protection against clicking a link while information stored in form input | |
* fields is not yet saved on the server. | |
* | |
* To enable edit protection, use: | |
* | |
* $(document).ready(function(){ | |
* EditProtection.init(); | |
* }); | |
* | |
* Copyright (c) 2013, T. Zengerink | |
* Licensed under MIT License. | |
* See: https://gist.github.com/raw/3151357/6806e68cb9cc0042b265f25be9bc25dd39f75267/LICENSE.md | |
*/ | |
var EditProtection = (function(){ | |
var ep = {}, | |
changedClass = "value-has-changed", | |
excludeClass = "excluded-edit-protection", | |
warningText = [ | |
"You have edited some of the fields, leaving this page will cause you to lose these changes.", | |
"\n\rAre you sure?" | |
].join(""); | |
// Ask if the user is sure to exit the page | |
ep.areYouSure = function(e){ | |
ep.changesAreMade() && ! confirm(warningText) && e.preventDefault(); | |
}; | |
// Bind on change functionality to element | |
ep.bindOnChange = function(){ | |
var orig = this.type == "checkbox" ? this.checked : this.value; | |
$(this).bind("change", function(){ | |
$(this).toggleClass(changedClass, (this.type == "checkbox" ? this.checked : this.value) !== orig); | |
}); | |
}; | |
// Return if any changes have been made | |
ep.changesAreMade = function(){ | |
return !! $("."+ changedClass).length; | |
}; | |
// Initialize edit protection by binding events | |
ep.init = function(){ | |
$("a").not("."+ excludeClass).bind("click", ep.areYouSure); | |
$("input,select,textarea").not("."+ excludeClass).each(ep.bindOnChange); | |
}; | |
return ep; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment