modify serialize form function to take input ID in

2019-08-27 15:43发布

I have a JavaScript function which iterates over a form to obtain input values based on the name of the input field. However, in order to satisfy API post request parameters, I need the input in the following JSON format:

{
    "name": "mobile offers",
     "group_id": "35"
}

where the "name" field is the result of input from a textbox and the "group_id" field is the result of the selection of an option via checkbox. How can I change this function so that it takes the input based on name for the textbox field and id for the checkboxes?

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

I've tried doing it using two separate functions, one for name and one for id, but cant figure out how to put the output together and it doesn't make sense to serialize the form twice.

1条回答
我命由我不由天
2楼-- · 2019-08-27 16:18

If name of checkboxes is incorrect, can simply change them to value of id before serializing

$(':checkbox').attr('name',function(){
 return this.id;
});
 /* now serialize form*/
查看更多
登录 后发表回答