Reputation: 1237
I have a form that I want to get all his values, and convert them to json object.
the problem is that I not get the multiselect fields, just one field. this is my code what I am missing?
let reportDropDowns = $('#getReport').serialize();
reportDropDowns = decodeURI(reportDropDowns);
let reportDropDownsJson = {};
reportDropDownsJson = JSON.parse('{"' + reportDropDowns.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) });
Upvotes: 0
Views: 639
Reputation: 6363
Instead of serializing the data directly via .serialize()
, you should instead use .serializeArray()
to get the data as an array. You can then manipulate the array into an object/JSON. Try this
let reportDropDownsJson = {};
$('#getReport').serializeArray().forEach(({name, value}) => {
if( reportDropDownsJson.hasOwnProperty(name) ){
if( !Array.isArray(reportDropDownsJson[name]) ){
reportDropDownsJson[name] = [reportDropDownsJson[name]];
}
reportDropDownsJson[name].push(value);
}else{
reportDropDownsJson[name] = value;
}
});
Upvotes: 1