How to submit an array of form elements?
Unanswered
Transvaal lion posted this in #help-forum
Transvaal lionOP
In HTML/PHP, I can generate a form and deal with it like:
Then:
I'm trying to mimic the same pattern in NextJS. The relevant page content looks like:
The form's onsubmit is very basic:
On form submission, the JSON returned is a flat array with the last row's data (except for the checkbox, but I understand that).
Adding square brackets to the element name just changes the name of the form element.
How do I submit a form with an array of form elements?
<input name="xyz[]" value="Lorem" />
<input name="xyz[]" value="ipsum" />
<input name="xyz[]" value="dolor" />
<input name="xyz[]" value="sit" />
<input name="xyz[]" value="amet" />Then:
$_POST['xyz'][0] == 'Lorem'
$_POST['xyz'][4] == 'amet'I'm trying to mimic the same pattern in NextJS. The relevant page content looks like:
<TableBody>
{Tracks.map((Track) => (
<TableRow key={Track.id}>
<TableCell><input type="checkbox" name="selected" /></TableCell>
<TableCell>{Track.title}</TableCell>
<TableCell><DatePicker selected={startDate} onChange={(date) => setStartDate(date)} showTimeSelects dateFormat="Pp" /></TableCell>
<TableCell><input type="text" name="conditions" /></TableCell>
</TableRow>
))}
</TableBody>The form's onsubmit is very basic:
async function onSubmit(event) {
event.preventDefault()
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/tracks', {
method: 'POST',
body: formData,
})
// Handle response if necessary
const data = await response.json()
console.log(data)
// ...
}/api/tracks just returns JSONified form data.On form submission, the JSON returned is a flat array with the last row's data (except for the checkbox, but I understand that).
Adding square brackets to the element name just changes the name of the form element.
How do I submit a form with an array of form elements?
2 Replies
let say you have below html
<input name="xyz" value="Lorem" />
<input name="xyz" value="ipsum" />
<input name="xyz" value="dolor" />
<input name="xyz" value="sit" />
<input name="xyz" value="amet" />then on the server you can grab the array with
formData.getAll("xyz")