Skip to content

Instantly share code, notes, and snippets.

@andykeith
Created February 4, 2019 16:44
Show Gist options
  • Save andykeith/4786cf4d4628924258b4a34f53aac875 to your computer and use it in GitHub Desktop.
Save andykeith/4786cf4d4628924258b4a34f53aac875 to your computer and use it in GitHub Desktop.
Serialize a form in jQuery, handling radio/checkbox arrays.
/**
* Parse a form to an object in the format: { input1: 'value', input2: 'some value', etc }.
*
* @param {jQuery} $form The form to parse
* @returns {Object} The serialized form
*/
function serializeForm( $form ) {
var serialized = $form.serializeArray(),
s = '', name = '', prefix = '', index = 0,
data = { }, arrayNames = { };
for ( s in serialized ) {
name = serialized[s]['name'];
// Handle checkboxes and radios which can have multiple values under the same input name.
if ( '[]' === name.slice( -2 ) ) {
index = name in arrayNames ? arrayNames[name] : 0;
arrayNames[name] = index + 1;
prefix = name.slice( 0, name.length - 2 );
name = prefix + '[' + index + ']';
}
data[name] = serialized[s]['value'];
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment