Skip to content

Instantly share code, notes, and snippets.

Created August 18, 2012 17:37
Show Gist options
  • Save anonymous/3388634 to your computer and use it in GitHub Desktop.
Save anonymous/3388634 to your computer and use it in GitHub Desktop.
Serialize JS
(function ($) {
$.fn.serialize = function (options) {
return $.param(this.serializeArray(options));
};
$.fn.serializeArray = function (options) {
var o = $.extend({
checkboxesAsBools: false
}, options || {});
var rselectTextarea = /select|textarea/i;
var rinput = /text|number|hidden|password|search|date|datetime|time/i;
return this.map(function () {
return this.elements ? $.makeArray(this.elements) : this;
})
.filter(function () {
return this.name && !this.disabled &&
(this.checked
|| this.type === 'checkbox'
|| rselectTextarea.test(this.nodeName)
|| rinput.test(this.type));
})
.map(function (i, elem) {
var val = $(this).val()==null?"":$(this).val();
return val == null ?
null :
$.isArray(val) ?
$.map(val, function (val, i) {
return { name: elem.name, value: val };
}) :
{
name: elem.name,
value: (this.type === 'checkbox') ? //moar ternaries!
(this.checked ? 'true' : 'false') :
val
};
}).get();
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment