Skip to content

Instantly share code, notes, and snippets.

@yehchge
Forked from lukemorton/example.js
Last active August 29, 2015 14:07
Show Gist options
  • Save yehchge/d4a4ab23da79a76a5534 to your computer and use it in GitHub Desktop.
Save yehchge/d4a4ab23da79a76a5534 to your computer and use it in GitHub Desktop.
// 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