Skip to content

Instantly share code, notes, and snippets.

@lukemorton
Created November 22, 2012 13:51
Show Gist options
  • Save lukemorton/4131266 to your computer and use it in GitHub Desktop.
Save lukemorton/4131266 to your computer and use it in GitHub Desktop.
jQuery plugin for watching a form for changes then detecting if it has changed
// In this example we detect if a user clicks a link to travel elsewhere
// but has made changes to a form. If they have changed the form it prompts
// them to confirm before continuing.
jQuery(function ($) {
var $form = $('form').watchChanges();
$('a').click(function (e) {
if ($form.hasChanged() and ! confirm('Continue without saving changes?')) {
e.preventDefault();
}
});
});
// Written by Luke Morton, licensed under MIT
(function ($) {
$.fn.watchChanges = function () {
return this.each(function () {
$.data(this, 'formHash', $(this).serialize());
});
};
$.fn.hasChanged = function () {
var hasChanged = false;
this.each(function () {
var formHash = $.data(this, 'formHash');
if (formHash != null && formHash !== $(this).serialize()) {
hasChanged = true;
return false;
}
});
return hasChanged;
};
}).call(this, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment