Question

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;
};

No correct solution

OTHER TIPS

You'll have to find each element within the form by name and check whether it's a checkbox.

But note that it's perfectly valid to have multiple text boxes, passwords, file uploads, etc. as well. Nothing defines a form input as being "multiple" in any way except the presence of two successful controls with the same name when you happen to look at the form.

It might be easier to just deal with this on the backend when you know you need an array. Or submit the form with plain old form encoding rather than JSON, and let your backend's HTTP library deal with it. (Most of them let you do something like request.GET.getall('mycheckbox') to always get a list back.)

If you do not want to modify the plugin's code directly, you can simply modify the object afterward.

var formData = $('form').serializeObject(),
    mycheckboxVal = formData.mycheckbox;

if (!$.isArray(mycheckboxval)) {
    formData.mycheckbox = [mycheckboxval];
}

//then you serialize
var jsonData = JSON.stringify(formData);

You could also perform the same logic server-side if you prefer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top