0

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

3
  • Kindly add the actual HTML of the form to the question. Commented Feb 15, 2022 at 15:47
  • ^ agreed with the above, the serialize method will only return successful controls which are defined in the official documentation, meaning if your HTML is not proper peer W3C you might see problems with what you are looking to achieve. See: api.jquery.com/serialize Commented Feb 15, 2022 at 15:49
  • how I can copy the html from the dom Commented Feb 15, 2022 at 16:01

1 Answer 1

1

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;
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Hey it worked however I can not manipulate it to json
You can use JSON.stringify(reportDropDownsJson) to convert it to JSON string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.