Tutorial :Add current row into table


i have this structure of html table:

    <table id="test">       <thead>         <tr>          <td></td>          <td></td>          <td></td>          <td></td>         </tr>       </thead>       <tbody>         <tr>          <td><a href="javascript:{}" onclick="addPiece(1)">add</a></td>         </tr>         <tr>          <td></td>         </tr>         <tr>          <td></td>         </tr>         <tr>          <td></td>         </tr>        </tbody>       </table>  

I need clone row in user defined place of table body. User can define place to clone this block by clicking to some link. For example <a href="javascript:{}" onclick="addPiece(1)">add</a> must clone block after the first block in table. How can i do that?


For example you want to add your mentioned block before place 2 then probably this will do fine for you

function addPiece(position) {      $("#YOURBLOCK").clone().insertBefore( $('#test > tbody > tr').get(position) );  }  

Similarly for after insertion

function addPiece(position) {      $("#YOURBLOCK").clone().insertAfter( $('#test > tbody > tr').get(position) );  }  


This answer will help. Add table row in jQuery

Actually in the specified answer it is adding row to the end of the table. But you will not need that selector if you are getting the row from user events.


You need the ID of the field, after which the row should be inserted. Then you do:

$('#tr-id').after('<tr><td>New line</td></tr>');  


You can add a new row after or before a specified row To add row before specified index

$("<tr><td>0</td></tr>").insertBefore( $('#test > tbody > tr').get(0) );  

To add row after specified index

$("<tr><td>0</td></tr>").insertAfter( $('#test > tbody > tr').get(0) );  

Similary you can use .before() and .after() methods as well.


Here is a very simple function that will create a <tr>, put a <td> inside it and a 5 inside the td. Then it will add it to the end of the tbody in your #test table.

function(){      var tr = $('<tr/>');      var td = $('<td/>');      td.text('5');      tr.append(td);      $('#test tbody').append(​​​​​​​​​​​​​​​​​​tr);  }  

The var tr and var td can be skipped if you use an HTML string in their place like JochenJung suggested, but doing it this way allows you to, e.g., add classes to the tr, or a colspan to the td.

You could also do something like

$('#table tbody').append($('#table tr:last-child').clone())  

but note that this requires the #table to be looked up twice, and doesn't give you a handle on the elements for modification.

(I saved this example here so you can play with it: http://jsbin.com/aduko/edit)

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »