Sometimes you need to know if the user has changed any of the fields on the page. I wrote a jModified jQuery plugin that will allow you to do just that. It works by hooking it up to form fields, and providing a callback method that will give you the form id, the original value, and the new value. Unlike a simple handling of the change event the original value is preserved so you can see if it actually changed.
The form fields:
<label for="a">Field A:</label>
<input id="a" name="a" type="text" value="a value" />
<br/>
<label for="b">Field B:</label>
<input id="b" name="b" type="text" value="b value" />
<br/>
<label for="c">Field C:</label>
<input id="c" name="c" type="text" value="c value" />
The hookup:
<script>
$(function() {
$("input").modified( { onModified: valueChanged } );
});
var isPageDirty = false;
function valueChanged(id, previousVal, newVal) {
isPageDirty = true;
alert('The page is dirty. The value for ' + id + ' has changed from ' + previousVal + " to " + newVal);
}
</script>
The jModified Plugin:
(function($){
$.fn.modified = function(options) {
var defaults = {
onModified: function(id, previousVal, newVal) {
alert('The value for ' + id + ' has changed from ' + previousVal + " to " + newVal ); }
};
var options = $.extend(defaults, options);
this.each(function() {
$(this).data('originalValue', $(this).val());
});
return this.change(function() {
var newValue = $(this).val();
var originalValue = $(this).data('originalValue');
if(newValue != originalValue)
options.onModified($(this).attr("id"), originalValue, newValue);
});
};
})(jQuery);
Get the full source on
GitHub.