Thomas
Thomas

Reputation: 43

Convert dynamic list object in form to JSON with javascript

I have a form submission script that converts form inputs to JSON and submits with ajax. It works for the simple forms that I have used it for previously, but when I try to use it for lists it is not read correctly.

Inside the form there is a dynamic list of inputs that is generated by another script. The list items look like this:

<li><input type="checkbox" name="skill_list[]" value="10155"></li>

The function that reads the form looks like this:

var formToJSON = elements => [].reduce.call(elements, (data, element) => {

  data[element.name] = element.value;
  return data;

}, {});

Inside the event listener for the submit button, the function is called:

var data = formToJSON(this.elements);

And finally, before submission, the data is stringified:

var data = JSON.stringify(data);

The error occurs in the formToJSON function. Instead of creating an object with the name skill_list and a value like {10155, 10288, 10240} it creates an object with the name skill_list[] and the value is whatever the first value in the list is.

I've been trying to rewrite the function to recognize a list but I haven't been able to and I'm running out of ideas. Can someone please help guide me in the right direction?

PS. I would prefer to write this without jQuery.

Upvotes: 0

Views: 1402

Answers (2)

hsz
hsz

Reputation: 152216

You have to handle array of elements separately:

var formToJSON = elements => [].reduce.call(elements, (data, element) => {
  var isArray = element.name.endsWith('[]');
  var name = element.name.replace('[]', '');

  data[name] = isArray ? (data[name] || []).concat(element.value) : element.value;
  return data;
}, {});

Upvotes: 1

Ram Venkat
Ram Venkat

Reputation: 94

If you want to convert form data into json object, try the following

var formData = JSON.parse(JSON.stringify($('#frm').serializeArray()));

Upvotes: 0

Related Questions