I'm trying to create a form where the users can dynamically anothers student to a form. The form should be submitted to the server as an array of students, each with a first and last name.
Desired outcome:
[
{
first_name: "Bob",
last_name: "Smith"
},
{
first_name: "John",
last_name: "Joe"
}
]
For some reason the code below puts all the first_name 's and all the last_name 's into arrays when the form is submitted. Specifying name="students[][first_name]" doesn't seem to solve the problem for me.
Actual outcome:
[
{
"first_name": [
"Bob",
"John"
],
"last_name": [
"Smith",
"Joe"
]
}
]
HTML
<form class="col-md-5" action="/insert" method="post">
<div class="form-group" id="student-controls">
<div class="student-entry input-group">
<input name="students[][first_name]" class="form-control param-name" type="text"/>
<input name="students[][last_name]" class="form-control col-md-2 param-unit-type" type="text"/>
<button class="btn btn-success student-add" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
JS (to dynamically add student form fields)
$(document).on('click', '.student-add', function(e)
{
e.preventDefault();
var controlDiv = $('#student-controls'),
currentEntry = $(this).parents('.student-entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlDiv);
newEntry.find('input').val('');
controlDiv.find('.student-entry:not(:last) .student-add')
.removeClass('student-add').addClass('student-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
index.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/insert', function(req, res) {
console.log(JSON.stringify(req.body.students, null, 2));
});
This is probably not the cleanest way... but it works. The idea is that the HTML contains
<input name="students[0][first_name]" class="form-control param-name" type="text" />
<input name="students[0][last_name]" class="form-control col-md-2 param-unit-type" type="text" />
Then, on the click handler, after you add a new div, you edit all the inputs so that they are properly indexed.
newEntry.appendTo(controlDiv);
$(".student-entry input[name*=first_name]").each(function(i) {
$(this).attr('name', 'students[' + i + '][first_name]');
});
$(".student-entry input[name*=last_name]").each(function(i) {
$(this).attr('name', 'students[' + i + '][last_name]');
});
This produces this output:
{
"students": [
{
"first_name": "luke",
"last_name": "skywalker"
},
{
"first_name": "han",
"last_name": "solo"
}
]
}
Note that for this to work, bodyParser must be configured with extended: true.
app.use(bodyParser.urlencoded({ extended: true }));