Skip to content

Instantly share code, notes, and snippets.

@Onheiron
Created November 11, 2012 16:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Onheiron/4055352 to your computer and use it in GitHub Desktop.
Save Onheiron/4055352 to your computer and use it in GitHub Desktop.
Form 2 JSON - jQuery Plugin
$.fn.toJSO = function () {
var obj = {},
$kids = $(this).children('[name]');
if (!$kids.length) {
return $(this).val();
}
$kids.each(function () {
var $el = $(this),
name = $el.attr('name');
if ($el.siblings("[name=" + name + "]").length) {
if (!/radio|checkbox/i.test($el.attr('type')) || $el.prop('checked')) {
obj[name] = obj[name] || [];
obj[name].push($el.toJSO());
}
} else {
obj[name] = $el.toJSO();
}
});
return obj;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment