Home > Enterprise >  How to get form data with multi select in checkboxs - javascript
How to get form data with multi select in checkboxs - javascript

Time:02-17

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

this is my html enter image description here

CodePudding user response:

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;
    }
});
  • Related