2

Each cell has some field, text input, radio buttons or select.

Am I forced to name the fields in such a way so the names embody the row and column indexes? like "data[row][col]"? It is kind of a hassle to dynamically create those field names when adding rows or columns to the table..

Can jQuery magic be used here?

Yoni Baciu
  • 2,667
  • 1
  • 22
  • 28

3 Answers3

1

Sure can, look here:

// This assumes that you've wrapped the form #myform around the input
$('#myform').submit(function() {
    $('#mytable tr').each(function(n, elem) {
        $('td', elem).each(function(m) {
            $('input:text, input:radio, textarea, select')
                .attr('name', 'data['+n+']['+m+']');
        });
    });

    // Do some validation or just let it submit :D
});

Here you go!

aefxx
  • 24,835
  • 6
  • 45
  • 55
1

of course jquery magic can be used! just name your cells what they are and include a hidden field with the id, for instance:

<tr>
    <td class="firstname"><input /></td>
    <td class="lastname"><input /></td>
    <td class="address"><input /></td>
    <td class="phone"><input /></td>
    ... 
    <td class="whatever">
        <input />
        <input type="hidden" class="itemId" value="[the id]" />
    </td>
</tr>

when you want to update a certain row, grab the row by doing something like

var row = $('tr').find('.itemId[value=' + id + ']');
// if you're in an event handler: 
var id = $(this).parents('tr').find('.itemId').val(); //gets you the id you want

now you can do things like:

var firstname = row.find('.firstname :input').val(); //etc..

compile them into a JSON object:

var data = {"itemId": id, "firstname": firstname, "lastname": lastname, ...etc };

and submit via $.post(), $.ajax() or $.get(). Easy!

Jason
  • 51,583
  • 38
  • 133
  • 185
  • Thank you for your answer. But how will I deal with dynamically added columns? How will the fields in those new cells be named? – Yoni Baciu Nov 17 '10 at 16:34
  • whatever you want to name them. when you create them you know what they are, even though they're dynamic, right? people don't just create random dynamic data... – Jason Nov 17 '10 at 20:21
0

Say you have a table with y columns and x rows. You can simply grab the cell data out of each one using the nth-child and gt selectors. For example, to select the cells of the first column (exluding the 'header' cell) you can do:

$("#tableId td:gt(0):nth-child(1)").css("color", "red");

So to grab the form element values from each cell you can do something like this, using .map:

var values = $("#tableId td:gt(0):nth-child(1) :input").map(function() {
    return this.value;
}).get();
alert(values);

Demo: http://jsfiddle.net/Nunhk/3/

karim79
  • 339,989
  • 67
  • 413
  • 406