Reputation: 2451
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.
Upvotes: 0
Views: 852
Reputation: 171679
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*/
Upvotes: 1