I'd like to post an array of n length to a form. What's the best way to handle this?
The object is a Timesheet, which has a date, and an array of Lines.
Lines have a duration, category, and note field.
My form has a date field, and one line to start, and jQuery appends more lines as necessary.
I know I need to use bracket notation somehow, but I don't know how considering I have two objects nested.
FWIW, the application end of things is in Node.js and express.
<form id="timesheet" method="POST" action="/timesheets">
<label>date for timesheet</label>
<input type="date" name="date"/><br/>
<ol id="timesheet-list">
<li>
<input type="number" name="hours" min="0" value="0" step=".25"/>
<input type="text" name="category"/>
<input type="text" name="details"/>
</li>
</ol>
<input type="submit"/>
</form>
<a id="addItem" href="#">Add a new line item</a>
<script type="text/javascript">
$('#addItem').click(function(e){
e.preventDefault();
$('#timesheet-list').append('<li><input type="number"> <input type="text"> <input type="text"></li>');
});
</script>
You want to format you data in JSON
to POST to your form?
Your JSON
object would look something like this.
// Entire object is a representation of a 'Timesheet'
{
date: '8-8-2012',
lines: [ // Array of objects, each storing a duration, catagory and note.
{
duration: 0,
catagory: 'whatever',
note: 'whatever'
},
{ // Have as many of these as you please.
duration: 123,
catagory: 'another',
note: 'moar notes'
},
]
}
When you receive this object, you can access the data like so:
data = getTimesheet(); // Assume this function gets the above JSON
data.date;
for(var i=0; i<data.lines.length; i++) {
data.lines[i].duration;
data.lines[i].catagory;
data.lines[i].note;
}
I think you could serialize your input values if you want to submit it as a JSON data using the jQuery serializeArray
method
$('form').submit(function() {
alert($(this).serializeArray());
return false;
});
NOTE that for the above to work your <input ...>
must have a name
attribute.
For others who may be looking to encode more complex data (object types) into form-data this answer here is helpful. Basically, it uses the serializeArray function to turn it into a JavaScript object (following code is included because the link may go inactive over time)
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) { //check to see if name attribute exists
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Using the function
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});