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.

/* @projectDescription jQuery Serialize Anything - Serialize anything (and not just forms!)
 * @author Bramus! (Bram Van Damme)
 * @version 1.0
 * @website: http://www.bram.us/
 * @license : BSD
*/
(function($) {
	$.fn.serializeAnything = function() {
		var toReturn	= [];
		var els 		= $(this).find(':input').get();
		$.each(els, function() {
			if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
				var val = $(this).val();
				toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
			}
		});
		return toReturn.join("&").replace(/%20/g, "+");
	}
})(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!

javascript, Webdevelopment , , ,

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

  1. Bob says:

    Hi, I just came across this. Simple, convenient, and just what I needed. Thanks!

  2. Florin says:

    I tried $(‘#myElement’).serialize() and it did the same thing :)

  3. Bramus! says:

    @Florin: pre jQuery 1.3 that didn’t work ;)

  4. ?????? says:

    That’s really works! I used jQuery 1.3. Thanks!

  5. iwanttobelieve says:

    Omg this is what I am looking for, thank you a lot!

  6. Miro says:

    Very usefull indeed!

  7. Reckless says:

    Does not work with a multiple select box or file inputs.

  8. D-Cis says:

    let jQuery do the stuff for you…

    $(‘#ingreso_detalle tbody tr:first td:first’)
    .find(‘[name]:input’) //since version 1.0
    .clone() //since version 1.0
    .wrap(”) //since version 1.0
    .serialize() //since version 1.0

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>