Skip to content

Instantly share code, notes, and snippets.

@datchley
Last active August 29, 2015 13:58
Show Gist options
  • Select an option

  • Save datchley/9967558 to your computer and use it in GitHub Desktop.

Select an option

Save datchley/9967558 to your computer and use it in GitHub Desktop.
Dead simple function to serialize a form as a JSON object, using '.' notation in the field 'name' attribute and only serializing fields with a class of 'serialize'.
window.serializeFormJSON = function(f) {
var json = {},
$f = f.jquery ? f : $(f);
$('input.serialize, select.serialize, textarea.serialize', $f).each(function(index, node) {
var keypath = $(this).attr('name').split('.'),
key = keypath.pop(),
item = json;
for (var i=0, l=keypath.length; i < l; i++) {
if (!(keypath[i] in item)) {
item[keypath[i]] = {};
}
item = item[keypath[i]];
}
item[key] = $(this).val() || null;
});
return json;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment