New jQuery Plugin - autoSave()

Posted by daemach on March 28, 2007

autoSave is the result of one too many user complaints about losing data due to session timeouts, power outages, meteor strikes and other issues beyond my control. You can feed it one or all of your form fields and it will do an ajax post to your server whenever any of those values change, with a delay built in for text-type fields to minimize the number of ajax calls your application makes.

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:

Text only
  1. $(document).ready(function(){
  2.    $(":input").autoSave(function(){
  3.       var ele = new Object();
  4.       // remember that this function runs in the scope of the element itself.
  5.       ele[this.name] = (this.type =="checkbox") ? this.value + "|" + this.checked : this.value;
  6.       $.post("test.cfm", ele, function (data) {$("#ResultDiv").empty().append(data);} )
  7.    });
  8. });
Highlighting by GeSHI

Download here: jquery.autoSave.js

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. ProDevStudio Wed, 16 May 2007 01:53:11 Eastern Daylight Time

    You need to provide more documentation on how to use this plug-ins!

Comments