Skip to content

Instantly share code, notes, and snippets.

@searls
Created April 3, 2012 22:33
Show Gist options
  • Save searls/2296000 to your computer and use it in GitHub Desktop.
Save searls/2296000 to your computer and use it in GitHub Desktop.
A poor man's helper for tracking dirty fields.
var tracksDirtyFields = (function($inputs) {
var inputValue = function($input) {
return $input.is(':checkbox,:radio') ? $input.is(':checked') : $input.val();
},
countFields = function() {
return $(':input').length;
},
readFields = function() {
return _({}).tap(function(values) {
_($(':input')).each(function(input) {
values[$(input).attr('name')] = inputValue($(input));
});
});
},
initialCount = countFields(),
initialValues = readFields();
return {
isDirty: function() {
return initialCount !== countFields() || !_(initialValues).isEqual(readFields());
}
};
})();
//so at any point, you can check dirtiness with
tracksDirtyFields.isDirty()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment