Overkill? Possibly, but this was more of an experiment than anything and since it could prove useful in rare circumstances I'm making it available.
Please be kind - I have no formal programming training of any kind, so the code might be somewhat lacking in elegance. In fact, "somewhat" might be a bit of an understatement...
Usage: $("yourFormInputs").autoSave( Function, Map );
Function: Any ajax function. The function is called in the scope of the element itself so "this" refers to the element's properties: this.id, this.value, this.checked, etc.
Map: Key/value pairs as parameters
- delay(ms) - for text fields, how long to wait before posting. default 1000ms
- beforeClass - class to apply to the element when the value has changed
- afterClass - class to apply to the element after the ajax call has returned
- onChange - function to run when the value changes. By default applies beforeClass
- preSave - function to run just before the ajax function is run. Returning a boolean"false" from this function will prevent the ajax call from running and reverts the field to its previous value. All other return values allow the ajax callto run normally. ( Of limited use, but why not... )
- One possible use: { preSave : function (){ return confirm('are you sure?'); } }
- postSave - function to run when the ajax call completes. By default applies afterClass
Caveats: Checkboxes have to be handled specially since they don't have separate values for checked and unchecked states. See below for one possible solution.
Example: ( I need to find a script formatter...)
$(document).ready(function(){
$(":input").autoSave(function(){
var ele = new Object();
// remember that this function runs in the scope of the element itself.
ele[this.name] = (this.type =="checkbox") ? this.value + "|" + this.checked : this.value;
$.post("test.cfm", ele, function (data) {$("#ResultDiv").empty().append(data);} )
});
});
You can download it here: jQuery.autoSave.js