Side navigation
#11312 closed enhancement (duplicate)
Opened February 09, 2012 05:07PM UTC
Closed February 09, 2012 05:44PM UTC
Last modified February 09, 2012 05:44PM UTC
Suggestion: .serializeObj()
Reported by: | wheresrhys@gmail.com | Owned by: | |
---|---|---|---|
Priority: | undecided | Milestone: | None |
Component: | unfiled | Version: | |
Keywords: | Cc: | ||
Blocked by: | Blocking: |
Description
It'd be useful to add a .serializeObj() method. At present, after running serializeArray() one must loop through the array checking each entry for its name and eventually getting to the value. If there was an option to serialize a form as a simple key value object it'd eliminate the need to run these loops and make form data available in a far more easily interchangeable format for passing around as parameters
In fact, it could be a good API to offer
.serialize([type]) (type = "string", "object" or "array"). I've had a go at implementing this below (not sure if I got the multivalued field bit right though)
serialize: function(type) { var obj, els = this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }); if (type === "object") { els.each(function( i, elem ){ var val = jQuery( this ).val(); if(val != null) { if (jQuery.isArray( val )) { val = jQuery.map( val, function( val, i ){ return val.replace( rCRLF, "\\r\\n" ); }) } else { val = val.replace( rCRLF, "\\r\\n" ); } } obj[elem.name] = val; }) return obj; } else { els = els.map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\\r\\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\\r\\n" ) }; }).get(); } return (type === "array") ? els : jQuery.param( els ); } }, serializeArray: function() { return this.serialize("array"); });