« | Home | »

jQuery.serializeAnything : Serialize anything (and not just forms!)

Code snippet I found somewhere in my archive: jQuery.serializeAnything() is a jQuery Extension that serializes any element you specify, in contrast to jQuery's builtin serialize() function which is limited to serializing form elements only.

JavaScript:
  1. /* @projectDescription jQuery Serialize Anything - Serialize anything (and not just forms!)
  2. * @author Bramus! (Bram Van Damme)
  3. * @version 1.0
  4. * @website: http://www.bram.us/
  5. * @license : BSD
  6. */
  7.  
  8. (function($) {
  9.           
  10.     $.fn.serializeAnything = function() {
  11.        
  12.         var toReturn    = [];
  13.         var els         = $(this).find(':input').get();
  14.        
  15.         $.each(els, function() {
  16.             if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
  17.                 var val = $(this).val();
  18.                 toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
  19.             }
  20.         });   
  21.                
  22.         return toReturn.join("&").replace(/%20/g, "+");
  23.        
  24.     }
  25.  
  26. })(jQuery);

Usage is simple: place the contents above in a .js file (jquery.serializeanything.js for example), refer to that file from your head element AFTER you referenced the jquery.js file, and use it just as you would call the serialize() function in your code: $('#myElement').serializeAnything().

Hf!

Spread the word!

  • del.icio.us
  • digg
  • Ma.gnolia

Tags

, , ,


About this entry

Best of Bram.us