3

I need to dynamically create (insert) a new table row every time user presses button (using Ajax). My partial view structure:

    <tr>
         <td><td>
         <td><td>
         ...
    </tr>

When I need insert new row at the end I can do something like this:

    element_table.innerHTML += ajax_data

But what I must do when I need to place it between other rows?

I can return only [td] elements and wrap them in [tr] clientside created element (tr.innerHTML = ajax_data) but I don't think this is a good idea.

Any ideas?

Are there any common practises?

pnuts
  • 58,317
  • 11
  • 87
  • 139
Anton Putov
  • 1,951
  • 8
  • 34
  • 62
  • would you be willing to rebuild the entire table? In other words, when there's a change, call a partial that rebuilds the table along with your new td? – Dave Alperovich Jan 29 '13 at 23:08
  • I dont think about it.In my case I can do this.But what if the table is big?Then new rows must inserted with ajax. – Anton Putov Jan 29 '13 at 23:12

1 Answers1

2

The easiest way is to use jQuery with your Ajax response. It can be as simple as

$('#table').append(response) 

to append a row. It's also possible to insert the new row at a specific index:

$('#my_table > tbody > tr').eq(index).after(response);

Note that index is 0 based.

Community
  • 1
  • 1
mfanto
  • 14,168
  • 6
  • 51
  • 61