JSFiddle - React, Tailwind, and code Playground
HTML
<form>
<input type="checkbox" name="ch1" />
<input type="checkbox" name="ch2" />
<input type="checkbox" name="ch3" />
</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
jQuery.fn.mySerialize = function(options) {
// default values to send when checkbox is on or off
var settings = {
on: 1,
off: 0
};
// override settings if given
if (options) {
settings = jQuery.extend(settings, options);
}
// set all checkboxes to checked with the on/off setting value so they get picked up by serialize()
var $container = jQuery(this),
$checkboxes = $container.find("input[type='checkbox']").each(function() {
jQuery(this).val(this.checked ? settings.on : settings.off).prop('checked', true);
});
var serialized = ($container.serialize());
// properly turn the checkboxes back on or off after serializing
$checkboxes.each(function() {
var $this = jQuery(this);
$this.prop('checked', $this.val() == settings.on);
});
return serialized;
};
//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'
}));
});