Jeremy Worboys Jeremy Worboys - 1 year ago 53
Javascript Question

Multidimensional form array to JavaScript object

I am working on a Backbone app that requires the input of rows of data (read: an array of objects).

I have the form set out like so:

<td><input type="text" name="items[][qty]"></td>
<td><input type="text" name="items[][job_number]"></td>
<td><input type="text" name="items[][description]"></td>
<td><input type="text" name="items[][purchase_order]"></td>

with a dynamic number of rows.

I want to be able to retrieve the data in the form of:

items: [
qty: [val],
job_number: [val],
description: [val],
purchase_order: [val]

The closest solution I have found is by Aaron Shafovaloff but it doesn't support the arrays in the output (only objects). I could modify his code to do what I need but I figured I would ask here first since there is no point reinventing the wheel.

I am using jQuery and Underscore in my project so have access to their methods.

Answer Source

I have mine this way to get multiple rows of text boxes:

    aItems = new Array();
    $("table tbody tr").each(function(){
        var $this = $(this);

            job_number: $this.find('input[name="job_number"]').val(),


how about this:

    aItems = new Array();
    $("table tbody tr").each(function(){
        var items = {};

            items[$(this).attr('name')] = $(this).val();

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