Ucinorn Ucinorn - 4 years ago 188
HTML Question

Create a array from HTML form and serializeArray()

I am building a form to POST data via AJAX, and would like to be able to produce an array of similar objects from a list of inputs. I'd like to keep things simple by structuring my form to produce an array of objects instead of having to iterate through inputs manually:

This is the HTML I have at the moment:

<form id="form"
<input type="hidden" name="id" value="1">
<input name="quantity" min="0" type="text" value="10" />
<input type="hidden" name="id" value="2">
<input name="quantity" min="0" type="text" value="20" />
<input type="hidden" name="id" value="3">
<input name="quantity" min="0" type="text" value="30" />

var json = $('#form').serializeArray();

And my goal is to produce an array or object where each set of inputs is grouped as seperate objects:


What form structure or elements can I use to create an array similar to the one above? Is it possible to produce arrays and objects straight from HTML forms?

Edit to clarify: I'm looking for a way to create arrays using JUST HTML FORMS and the serialize command. For instance, some combination of feildsets, legends, form groupings or other complex attributes on forms that I am not aware of that can influence the output of serialization.

Answer Source

First of all, the markup you've used is essentially meaningless as far as form information goes. You've used elements with the same names, which means that they are not differentiated from each other. If you want the data to be meaningful, you need the names to be meaningful.

One convention (used mostly in PHP) is form input arrays. This is where the names use array bracket notation. There are special effects with this in PHP, but it doesn't mean anything special in JavaScript. I'll be using that convention here in case you're sending this data to a PHP script.

First, get rid of the hidden input elements, they don't serve any purpose. Next append the unique identifier to each name (in this case I've used [1], [2], and [3], but if not using PHP then simply 1, 2, and 3 would suffice).

After you've made the markup meaningful, it is relatively simple to get the form data using the FormData interface. Then it is just a matter of formatting the data as necessary.

const form = document.querySelector("#form");
const data = new FormData(form);
const format = e => ({ id: /\d+/.exec(e[0])[0], quantity: e[1] });
// [{"id":"1","quantity":"10"},{"id":"2","quantity":"20"},{"id":"3","quantity":"30"}]
<form id="form">
<input name="quantity[1]" min="0" type="text" value="10">
<input name="quantity[2]" min="0" type="text" value="20">
<input name="quantity[3]" min="0" type="text" value="30">

There's all sorts of things you could do from here as far as formatting the result goes. This is just a basic example to provide the result expected in your question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download