Created
November 22, 2012 13:51
-
-
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
This file contains hidden or 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
// 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(); | |
} | |
}); | |
}); |
This file contains hidden or 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
// 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