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: https://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!

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Join the Conversation

19 Comments

  1. 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

  2. Thanks for the snippet! But please use normal quotes in your code I spend an hour searching for the error that came up every time 🙁

  3. Hi,

    this function will serialize first time but if i move back to form n update a few values it wont show the result as new values but same old values.

Leave a comment

Leave a Reply to Diekiss Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.