Serialize extension
This handles check boxes that are not ticked.
by chrisloughnane
HTML
<form>
<input type="checkbox" name="ch1" />
<input type="checkbox" name="ch2" />
<input type="checkbox" name="ch3" />
<input type="text" name="ch4" />
</form>
<div>
<input type="button" id="serializeIt" value="Serialize">
</div>
<div>Demo 1: <span id="msg1"></span></div>
<div>Demo 2: <span id="msg2"></span></div>
<div>Demo 3: <span id="msg3"></span></div>
JavaScript
// Plugin
$.fn.mySerialize = function(options) {
var settings = {
on: 'on',
off: 'off'
};
if (options) {
settings = $.extend(settings, options);
}
var $container = $(this).eq(0),
$checkboxes = $container.find("input[type='checkbox']").each(function() {
$(this).attr('value', this.checked ? settings.on : settings.off).attr('checked', true);
});
var s = ($container.serialize());
$checkboxes.each(function() {
var $this = $(this);
$this.attr('checked', $this.val() == settings.on ? true : false);
});
return s;
};
//Demos
$("#serializeIt").on('click', function() {
$("#msg1").html($("form").mySerialize());
$("#msg2").html($("form").mySerialize({
on: 1,
off: 0
}));
$("#msg3").html($("form").mySerialize({
on: 'ein',
off: 'aus'
}));
});