Documentation
Implementing the Plugin
As with most jQuery plugins, implementing the plugin with its default settings takes a single line of code. Call the plugin after the selector that denotes the form or container element that encloses all of the form fields you want to track the status of:
$("#myForm").dirtyFields();
When used with its default settings, the plugin does the following:
- Whenever a text input, <textarea>, or <select> element is changed (such that the jQuery change event is triggered), the <label> element associated with the element (via the label's "for" attribute) will have the CSS class "dirtyField" added to it.
- Note: hidden fields are not included by default (since users cannot directly change their values), but you can add them to the mix and monitor changes to them via the public functions.
- Whenever a checkbox or radio button element is changed, the <span> sibling element that follows it will have the CSS class "dirtyField" added to it.
To change those defaults, or to access additional plugin functionality via the callbacks, you can pass in a collection of settings and callbacks as options, like so:
var options= { denoteDirtyForm: true, denoteDirtyOptions: true, trimText:true, preFieldChangeCallback: function(originalValue) { $("#callbackBox").append("preFieldChangeCallback run. Original value: " + originalValue + "&;lt;br />"); } }; $("#myForm").dirtyFields(options);
Any settings that you don't pass in will simply default to the setting's default value, and any callbacks you don't define will simply not execute.
Settings
Below is an alphabetical list of all of the optional settings you can use to alter the behavior of the plugin:
-
checkboxRadioContext
Default: "next-span"
Tells the plugin which DOM/page element to apply the dirty field CSS class to (which is set to "dirtyField" by default) when used with checkbox and radio elements. Possible values are:
- previous-element tag: a sibling DOM element that precedes the checkbox/radio button.
- next-element tag: a sibling DOM element that follows the checkbox/radio button (like the default setting of "next-span").
- closest-element tag: the closest DOM element of that tag, whether it be a sibling or a parent. Useful in forms where the <label> encloses the form field.
- id-for: the <label> element whose "for" attribute value matches the "id" attribute value of the checkbox/radio button.
- id-class: the DOM element who has a CSS class that matches the "id" attribute value of the checkbox/radio button.
- id-title: the DOM element whose "title" attribute value matches the "id" attribute value of the checkbox/radio button.
- name-for: the <label> element whose "for" attribute value matches the "name" attribute value of the checkbox/radio button.
- name-class: the DOM element who has a CSS class that matches the "name" attribute value of the checkbox/radio button.
- name-title: the DOM element whose "title" attribute value matches the "name" attribute value of the checkbox/radio button.
- self: the checkbox/radio button itself.
-
denoteDirtyOptions
Default: false
Tells the plugin whether or not to apply the dirty options CSS class (which is set to "dirtyOption" by default) to <select> options whose selection status has been changed from their original state.
-
denoteDirtyFields
Default: true
Tells the plugin whether or not to apply the dirty field CSS (which is set to "dirtyField" by default) to DOM form fields that have changed in the container element you applied the plugin to. You can set this to false if you only want to indicate that the overall form is dirty (by changing the "denoteDirtyForm" option to true).
-
denoteDirtyForm
Default: false
Tells the plugin whether or not to apply the dirty form CSS class (which is set to "dirtyForm" by default) to the container element you applied the plugin to.
-
dirtyFieldClass
Default: "dirtyField"
The name of the CSS class that will be applied to the appropriate contextual element when a form field is evaluated as being dirty.
-
dirtyFieldsDataProperty
Default: "dirtyFields"
When the plugin is applied to the container element (whether it be a form, a <div>, or something else), it stores all of the plugin settings in an object called "dF" that gets added to the container element via the jQuery data() function. This setting determines the name of the object property inside the "dF" object that will store an array of the names of all currently dirty form fields.
So if this setting was left with the default setting value of "dirtyFields", and you applied the plugin to a form with an id of "myForm", you could retrieve the array of dirty fields with the statement:
var dirtyFieldsArray= $("#myForm").data("dF").dirtyFields
The formChangeCallback callback function also provides access to the same array of dirty field names.
-
dirtyFormClass
Default: "dirtyForm"
The name of the CSS class that will be applied to the form or other container element if any of the form fields are dirty and the denoteDirtyForm setting is set to true.
-
dirtyOptionClass
Default: "dirtyOption"
The name of the CSS class that will be applied to any <option> element whose selection status has been changed from their original state if the denoteDirtyOptions setting is set to true.
Note that some CSS styles (such as "color") will not work on <option> elements ("font-style" and "font-weight", however, will work) and that Internet Explorer may not respect any CSS styling of options.
-
exclusionClass
Default: "dirtyExclude"
If you have a situation where certain form fields on your page should NOT be tracked for changes, you have two options:
- You can put the form fields that should be excluded outside of whatever container you apply the plugin to (the plugin doesn't have to act on the entire form; you can apply it to a block element within the form).
- You can add this exclusion CSS class to the form elements within your container that you want to be excluded.
Changes made to any form elements that have this exclusion CSS class will not be tracked and will not change the dirty/clean state of the form.
NOTE: all of the relevant public functions such as configureField will respect this exclusion class (they do not override it), so the exclusion CSS class must be removed from the DOM element if you want to programmatically add it to the collection of form fields being tracked by the plugin.
-
fieldOverrides
Default: {none:"none"}
Use the fieldOverrides object to specify form elements who are exceptions to the checkboxRadioContext, selectContextand textboxContext settings. For example, say you have eight <textarea> fields in your form. For most of them, you want the corresponding <label> element to receive the dirty field class, so you leave the textboxContext as the default "id-for". But for two of the <textareas>, with ids of "textA" and "textB" respectively, you want the <h3> elements with ids of "headlineA" and "headlineB" to receive the dirty field class. To make that happen, simply input the ids of the form elements as property names in the fieldOverrides object and input the ids of the contextual elements as their values, like so:
var settings= { fieldOverrides: { textA: "headlineA", textB: "headlineB" } };
-
ignoreCaseClass
Default: "dirtyIgnoreCase"
Adding this CSS class to a text/textarea input or single-option <select> element will cause the plugin to make a case-insensitive evaluation of whether the current input value and the starting input value are equivalent. You would use this in a situation where the case of the text is irrelevant (for example, text inputs that are converted to all-uppercase during server processing and storage).
-
startingValueDataProperty
Default: "startingValue"
When the plugin is applied to the container element, or when the formSaved public function is executed, the current value or state of the form elements is stored "within" each element using the jQuery data() function. The name of the property where this value is stored is determined by this setting.
So if this setting was left with the default value of "startingValue", you could retrieve the initial/saved value of a text element with the statement:
var originalValue= $("#textA").data("startingValue")
...or the initial/saved state of a checkbox (true if checked, false if not) with the statement:
var isChecked= $("#myVote").data("startingValue")
-
selectContext
Default: "id-for"
Tells the plugin which DOM/page element to apply the dirty field CSS class to (which is set to "dirtyField" by default) when used <select> elements. Same possible values as the ones listed under checkboxRadioContext.
-
textboxContext
Default: "id-for"
Tells the plugin which DOM/page element to apply the dirty field CSS class to (which is set to "dirtyField" by default) when used with text inputs, file inputs, password inputs, and textareas. Same possible values as the ones listed under checkboxRadioContext.
-
trimText
Default: false
When set to true, the plugin will ignore/throw out any leading or trailing spaces from the current value of the form field before comparing it with the original value of the form field (so a field changed from "Robert" to "Robert " will not be considered to be changed/dirty). Useful when you have server-side code that removes leading/trailing spaces before saving a value to the database.
Callbacks
The callbacks provided by the plugin are listed below in order of execution:
-
preFieldChangeCallback(Previous value,Dirty or not)
If you define a preFieldChangeCallback function using the settings, it will execute prior to the plugin functions that will evaluate whether or not a field is dirty. The following data is passed back to the callback function:
- A jQuery object representing the form field changed (accessible as "$(this)"). This is passed implicitly; it does not appear in the list of parameters.
- The initial/saved value of the form field, passed back as a parameter. For checkboxes and radio buttons, the value returned will be Boolean value denoting if the button/checkbox is checked. For multi-select drop-downs, the value returned will be an array of the values of the selected options.
NOTE: you can use this callback to interrupt the process of determing if the field is dirty or not by having it return a Boolean value of false.
var options= { trimText:true, preFieldChangeCallback: function(originalValue) { console.log("Form field " + $(this).attr("name") + " had starting/saved value of: " + originalValue); }, dirtyFieldsClass: "alteredField" }; $("#myForm").dirtyFields(options);
-
fieldChangeCallback(Previous value,Dirty or not)
This callback will execute just after the plugin functions that evaluate whether or not a field is dirty have completed, but before the function that detemines if the form or form field container is dirty (if the denoteDirtyForm setting is set to true). The following data is passed back to the callback function:
- A jQuery object representing the form field changed (accessible as "$(this)"). This is passed implicitly; it does not appear in the list of parameters.
- The initial/saved value of the form field, passed back as a parameter. For checkboxes and radio buttons, the value returned will be Boolean value denoting if the button/checkbox is checked. For multi-select drop-downs, the value returned will be an array of the values of the selected options.
- A Boolean value denoting if the field is now dirty (true) or not (false), passed back as a parameter.
var options= { trimText:true, fieldChangeCallback: function(originalValue,isDirty) { if(isDirty) { console.log("Form field " + $(this).attr("name") + " value changed from " + originalValue + " to " + $(this).val()); } else { console.log("Form field " + $(this).attr("name") + " value unchanged"); } }, dirtyFieldsClass: "alteredField" };
-
formChangeCallback(Dirty or not,Array of dirty field names)
If the denoteDirtyForm setting is set to true, this callback will execute after the plugin evaluates whether the form or form field container contains one or more dirty fields. The following data is passed back to the callback function:
- A jQuery object representing the form/form field container (accessible as "$(this)"). This is passed implicitly; it does not appear in the list of parameters.
- A Boolean value denoting if the form/form field container is now dirty (true) or not (false), passed back as a parameter.
- An array containing the names of all the form fields currently dirty.
var options= { trimText:true, formChangeCallback: function(isDirty,dirtyFieldsArray) { if(isDirty) { console.log("Form is dirty. Dirty form fields " + dirtyFieldsArray); } else { console.log("Form is clean"); } }, dirtyFieldsClass: "alteredField" };
Public Functions
The plugin comes with a number of public functions to help you utilize the plugin in a number of different scenarios. Each of these functions can be called as a property of the $.fn.dirtyFields object (as shown in the example code).
NOTE: All of these functions require the form or form field container that the plugin was applied to to be passed in as a parameter. You cannot use a different container element for that parameter: it must be the container that the main plugin function dirtyFields() was used with.
-
configureField(Object,Container object,Context,Override target)
This function lets you add the change event handler to any new form fields you add to the form dynamically after the page is loaded so that the plugin will process the new fields. Note that you will also need to use either the setStartingTextValue, setStartingSelectValue, or setStartingCheckboxRadioValue function on the new form field as well in order to set the field's initial, clean value/state. The parameters are:
- A single jQuery object to add the event handler to.
- The jQuery object representing the form or form field container.
- The type of form field the object is ("text","select", or "checkboxRadio").
- (Optional) The id attribute of the DOM element you want to receive the dirty field class if you want to override the typical plugin behavior associated with the type of form field cited in the third parameter (it essentially adds a new property to the fieldOverrides setting).
$.fn.dirtyFields.configureField($("#newTextInput"),$("#myForm"),"text");
-
formSaved(Container object)
Updates all of the initial/saved form field values and states to whatever the current values and states of the form fields are and marks the form fields and the form container as being clean (by removing all instances of the dirty field, dirty option, and dirty form CSS classes). You would use this function anytime the current form values are saved to the database via AJAX. It takes one parameter: the form/form container as a jQuery object.
$.fn.dirtyFields.formSaved($("#myForm"));
-
getDirtyFieldNames(Container object)
Returns the array containing all of the form field names currently marked as dirty.
$.fn.dirtyFields.getDirtyFieldNames($("#myForm"));
-
markContainerFieldsClean(Container object)
This function simply removes all instances of the dirty field, dirty option, and dirty form CSS classes from the specified container object (which is passed in as the sole parameter).
$.fn.dirtyFields.markContainerFieldsClean($("#myForm"));
-
rollbackCheckboxRadioState(Object(s),Container object,Process change)
Reverts the specified checkbox or radio button field(s) back to their initial/saved state (checked or unchecked). The plugin callbacks (unless bypassed) will be executed once for each checkbox/radio button you rollback. The parameters are:
- The jQuery object or objects to be rolled back.
- The jQuery object representing the form or form field container.
- (Optional, default is true) A Boolean value as to whether or not you want the plugin to evaluate whether or not the end result of this function makes the specified form fields dirty or not. Set this to false to bypass the plugin's usual behavior.
$.fn.dirtyFields.rollbackCheckboxRadioState($("input[name='ageRange']"),$("#myForm"),false);
-
rollbackForm(Container object)
Reverts all of the form fields within the specified form or form field container back to their initial/saved value. Works like the standard HTML "Reset" button, but when used in conjunction with the formSaved function, it will reset the values of the form back to whatever values the form had when the formSaved function was executed, instead of to the values the form had when the web page was first loaded.
$.fn.dirtyFields.rollbackForm($("#myForm"));
-
rollbackSelectState(Object(s),Container object,Process change)
Reverts the specified <select> element(s) and their options back to their initial/saved value/state. The parameters are:
- The jQuery object or objects to be rolled back.
- The jQuery object representing the form or form field container.
- (Optional, default is true) A Boolean value as to whether or not you want the plugin to evaluate whether or not the end result of this function makes the specified form fields dirty or not. Set this to false to bypass the plugin's usual behavior.
-
rollbackTextValue(Object(s),Container object,Process change)
Reverts the specified text inputs, file inputs, password inputs, and/or <textarea> element(s) back to their initial/saved values. The parameters are:
- The jQuery object or objects to be rolled back.
- The jQuery object representing the form or form field container.
- (Optional, default is true) A Boolean value as to whether or not you want the plugin to evaluate whether or not the end result of this function makes the specified form fields dirty or not. Set this to false to bypass the plugin's usual behavior.
-
setStartingCheckboxRadioValue(Object(s),Container object)
This function allows you to set the saved state of one or more checkboxes/radio button elements to whatever the current state of the element is. You would used this function when dynamically adding a new checkbox/radio button element to an existing form so the plugin has an initial state for the element to use when evaluating if the element is dirty or not. The parameters are:
- The jQuery object or objects to have their initial values/states set.
- The jQuery object representing the form or form field container.
$.fn.dirtyFields.setStartingCheckboxRadioValue($("#addedBox"),$("#myForm"));
-
setStartingSelectValue(Object(s),Container object)
This function allows you to set the saved state of one or more <select> elements to whatever the current state of the element is. You would used this function when dynamically adding a new <select> element to an existing form so the plugin has an initial state for the element to use when evaluating if the element is dirty or not. The parameters are:
- The jQuery object or objects to have their initial values/states set.
- The jQuery object representing the form or form field container.
-
setStartingTextValue(Object(s),Container object)
This function allows you to set the saved state of one or more text inputs, file inputs, password inputs, and/or <textarea> elements to whatever the current state of the element is. You would used this function when dynamically adding a new text input/file input/password input/<textarea> element to an existing form so the plugin has an initial state for the element to use when evaluating if the element is dirty or not. The parameters are:
- The jQuery object or objects to have their initial values/states set.
- The jQuery object representing the form or form field container.
-
updateCheckboxRadioState(Object(s),Container object)
The plugin normally only evaluates if a form field is dirty when the form element's change event is triggered. Since programmatic alternations to a form field's state/value will not trigger a Javascript change event, use this function after you use Javascript to change the state of one or more checkboxes/radio buttons to prompt the plugin to evaluate whether or not the form field(s) are now dirty. The fieldChangeCallback (and optionally the formChangeCallback) will be executed once for each checkbox/radio button you update. The parameters are:
- The jQuery object or objects that have been updated/need to be evaluated.
- The jQuery object representing the form or form field container.
$.fn.dirtyFields.updateCheckboxRadioState($("input[name='ageRange']"),$("#myForm"));
-
updateFormState(Container object)
This function can be used in place of the individual updateCheckboxRadioState, updateSelectState, and updateTextState functions to evaluate the entire form or form field container for changes. The fieldChangeCallback (and optionally the formChangeCallback) will be executed once for each element in the specified container. The function takes a single parameter:
- The jQuery object representing the form or form field container.
$.fn.dirtyFields.updateFormState($("#myForm"));
-
updateSelectState(Object(s),Container object)
The plugin normally only evaluates if a form field is dirty when the form element's change event is triggered. Since programmatic alternations to a form field's state/value will not trigger a Javascript change event, use this function after you use Javascript to change the state of one or more <select> elements to prompt the plugin to evaluate whether or not the form field(s) are now dirty. The fieldChangeCallback (and optionally the formChangeCallback) will be executed once for each <select> element you update. The parameters are:
- The jQuery object or objects that have been updated/need to be evaluated.
- The jQuery object representing the form or form field container.
-
updateTextState(Object(s),Container object)
The plugin normally only evaluates if a form field is dirty when the form element's change event is triggered. Since programmatic alternations to a form field's state/value will not trigger a Javascript change event, use this function after you use Javascript to change the state of one or more text input, file input, password input and/or <textarea> elements to prompt the plugin to evaluate whether or not the form field(s) are now dirty. The fieldChangeCallback (and optionally the formChangeCallback) will be executed once for each text input, file input, password input and/or <textarea> you update. The parameters are:
- The jQuery object or objects that have been updated/need to be evaluated.
- The jQuery object representing the form or form field container.