Sunday, August 23, 2009

New jQuery Plugin dirtyFields: Bring Attention to Changed/Unsaved Fields

I just finished a project that included an administrative page where users could make changes to a parent record and numerous child records via multiple forms. All of the form submissions were done via AJAX, so I needed a way to illustrate which of the forms on the page contained changed or "dirty" data, and which forms had no unsaved changes.

This dirtyFields plugin is derived from the functions I wrote to handle that task in that project.

It applies a CSS class to a contextual DOM element associated with any form field that has been changed from its original value. For text inputs, <textarea>, and <select> elements, the <label> element associated with the field (via the "for" attribute) will be styled with the class. For <checkbox> and <radio> elements, you can specify the text associated with each element using "checkboxRadioTextTarget" plugin option (the default setting is "next span").

It works by storing the current value or state of each form field within the data store of the field using the jQuery data() function.  As the value or state of the form field is changed, its current value/state is compared to the one within its data store, and if they aren't equal the field is considered "dirty".  The plugin includes a function called "resetForm" that can be used after the form has been submitted to update the data store of each field with the new field value and mark all the form fields as clean.  There is also an option to apply a CSS class to the form itself to indicate whether or not it contains dirty fields.

(UPDATE: I've now added support for a "formIsDirty" callback function that can be used in conjunction with the "denoteFormDirty" option to run your own functions once a form has been determined to be clean or dirty.)

Links to a demo and documentation can be found below the following screenshot, which shows the style changes to the labels and text of form elements that have been changed:

Project homepage: https://bcswartz.github.io/dirtyFields-jQuery-Plugin/

No comments:

Post a Comment