views:

500

answers:

2

Hi folks,

Is there a jQuery plugin out there that can serialize a form, and then later restore/populate the form given the serialized value? I know the form plugin can serialize as a querystring, but I haven't found anything that will restore the form from the querystring.

What I'd like to do is serialize the form values, store as a cookie whenever the form changes, and then restore the form from the cookie (if it exists) when the page first loads.

I have found pieces of this puzzle out there (form plugin, cookie plugin, various autosave plugins that don't restore), but before I cobble something together from various parts, I wanted to make sure there wasn't a nice canned solution waiting for me out there.

Thanks!

Jim

+2  A: 

Here's a little something I rolled based on work of others, specifically serializeAnything:

/* jQuery.values: get or set all of the name/value pairs from child input controls   
 * @argument data {array} If included, will populate all child controls.
 * @returns element if data was provided, or array of values if not
*/

$.fn.values = function(data) {
 var els = $(this).find(':input').get();

 if(typeof data != 'object') {
  // return all data
  data = {};

  $.each(els, function() {
   if (this.name && !this.disabled && (this.checked
       || /select|textarea/i.test(this.nodeName)
       || /text|hidden|password/i.test(this.type))) {
    data[this.name] = $(this).val();
   }
  });
  return data;
 } else {
  $.each(els, function() {
   if (this.name && data[this.name]) {
    if(this.type == 'checkbox') {
     this.checked = (data[this.name] == $(this).val());
    } else {
     $(this).val(data[this.name]);
    }
   }
  });
  return $(this);
 }
};
Barnabas Kendall
Wow nice! Will save this for future use.
Tom R
Very cool! I'll just have to add a to/from JSON step so I can store the serialized state as a cookie. Thanks!
Jim Biancolo
A: 

Check out my jQuery Populate plugin:

http://www.keyframesandcode.com/code/development/javascript/jquery-populate-plugin/

Populates all form elements as well as labels and any contained HTML elements.

Dave Stewart