Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Serializing form to JSON when there is multiple inputs with same name

EDIT: not sure if knowing my back end is helpful or not, but I’ll be sending to Flask/Python.

trying to write a "form_to_json" serialization function in vanilla js to take a form ID and post that as valid json.

I’m stuck on parsing multiple inputs with the same names.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my current function, note the comment where I’m stuck.

// gather form elements and serialize inputs
    function form_to_json(form_id) {
        console.log(`Getting form with ID ${form_id}`);
        let obj_form = document.getElementById(form_id);

        // Create an object
        var obj = {};
        
        // Loop through each field in the form
        Array.prototype.slice.call(obj_form.elements).forEach(function (field) {
            // Skip some fields we don't need
            if (!field.name || field.disabled || ['file', 'reset', 'submit', 'button'].indexOf(field.type) > -1) return;
            
            // Handle multi-select fields
            if (field.type === 'select-multiple') {
                // Create an array of selected values
                var options = [];
                
                // Loop through the options and add selected ones
                Array.prototype.slice.call(field.options).forEach(function (option) {
                    if (!option.selected) return;
                    options.push(option.value);
                });
                
                // If there are any selection options, add them to the object
                if (options.length) {
                    obj[field.name] = options;
                }
                
                return;
            }
            
            // If it's a checkbox or radio button and it's not checked, skip it
            if (['checkbox', 'radio'].indexOf(field.type) > -1 && !field.checked) return;

            console.log(`${field.name}: ${field.value}`);
            
            // Add the value to the object
            if (field.name in obj) {
                // NOT SURE WHAT TO DO HERE
                obj[field.name].push(field.value);
            } else {
                obj[field.name] = field.value;
            }
        });
        
        // Return the object
        return obj;
    }

Here is a screenshot showing a visual of how the inputs are created by the end user.

enter image description here

With my current function code, I’m obviously only getting the last set of values for each redundant field name.

The front end allows user to dynamically add "criteria" rows (basically a set of those 3 inputs all named identically between each row).

My attempt was to check if the key already existed in the object, and if so, /do something/ but I can’t work out what that something is.

>Solution :

You can modify your if statement to convert the existing value into an array if it’s not one already. The if would look like this:

// Add the value to the object
if (field.name in obj) {
    if (!Array.isArray(obj[field.name])) {
      obj[field.name] = [obj[field.name]];
    }
    obj[field.name].push(field.value);
} else {
    obj[field.name] = field.value;
}

Below the working example with the modified code:

const form = document.getElementById('myform');
form.addEventListener('submit', function (e) {
  e.preventDefault();
  
  const serialized = form_to_json('myform');
  console.log(serialized);
});

// gather form elements and serialize inputs
    function form_to_json(form_id) {
        console.log(`Getting form with ID ${form_id}`);
        let obj_form = document.getElementById(form_id);

        // Create an object
        var obj = {};
        
        // Loop through each field in the form
        Array.prototype.slice.call(obj_form.elements).forEach(function (field) {
            // Skip some fields we don't need
            if (!field.name || field.disabled || ['file', 'reset', 'submit', 'button'].indexOf(field.type) > -1) return;
            
            // Handle multi-select fields
            if (field.type === 'select-multiple') {
                // Create an array of selected values
                var options = [];
                
                // Loop through the options and add selected ones
                Array.prototype.slice.call(field.options).forEach(function (option) {
                    if (!option.selected) return;
                    options.push(option.value);
                });
                
                // If there are any selection options, add them to the object
                if (options.length) {
                    obj[field.name] = options;
                }
                
                return;
            }
            
            // If it's a checkbox or radio button and it's not checked, skip it
            if (['checkbox', 'radio'].indexOf(field.type) > -1 && !field.checked) return;

            console.log(`${field.name}: ${field.value}`);
            
            // Add the value to the object
            if (field.name in obj) {
                if (!Array.isArray(obj[field.name])) {
                  obj[field.name] = [obj[field.name]];
                }
                obj[field.name].push(field.value);
            } else {
                obj[field.name] = field.value;
            }
        });
        
        // Return the object
        return obj;
    }
<form id='myform'>

<input name='crit' />
<input name='crit' />
<input name='crit' />
<input name='otherfied' />

<input type='submit' value='submit' />
</form>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading