public
Last active

JQuery Serialize Method with Checkbox False Output

  • Download Gist
JQuerySerializeCheckbox.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
(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|hidden|password|search/i;
 
return this.map(function () {
return this.elements ? $.makeArray(this.elements) : this;
})
.filter(function () {
return this.name && !this.disabled &&
(this.checked
|| (o.checkboxesAsBools && this.type === 'checkbox')
|| rselectTextarea.test(this.nodeName)
|| rinput.test(this.type));
})
.map(function (i, elem) {
var val = $(this).val();
return val == null ?
null :
$.isArray(val) ?
$.map(val, function (val, i) {
return { name: elem.name, value: val };
}) :
{
name: elem.name,
value: (o.checkboxesAsBools && this.type === 'checkbox') ? //moar ternaries!
(this.checked ? 'true' : 'false') :
val
};
}).get();
};
 
})(jQuery);

Modification to jquery serialize() method, to optionally support boolean serialization instead of standard http-form-submission-compliant checkbox serialization (name=value on true only).

Written by Thomas Danemar at http://tdanemar.wordpress.com/2010/08/24/jquery-serialize-method-and-checkboxes/, copied here for tracking/version control.

To easily consume serialization data generated with this "checkboxesAsBools" option, you can use the "jquery.deserialize" plugin: https://github.com/itsadok/jquery.deserialize

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.