0

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.

2 Answers 2

1

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

1 Comment

Thank you! This is perfect!
0

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

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

Comments

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.