I'm trying to serialize checkboxes on a form where several checkboxes will have the same name.
<input name="mycheckbox" type="checkbox" value="A"/>A</br>
<input name="mycheckbox" type="checkbox" value="B"/>B</br>
Using the serializeArray such as below everything works great. If both A & B are checked the JSON.stringify correctly represents the JSON as an array:
{"mycheckbox":["A","B"]}
However if I only have A checked the JSON is no longer represented as an array:
{"mycheckbox":"A"}
In my RESTful backend that's processing I need to consistently pass as an array. Is there any way of forcing stringify to represent it as an array?
var jsonData = JSON.stringify($('form').serializeObject());
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};