Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append new <tr> after current <tr>

Tags:

html

jquery

I have following table structure.

<table>
    <tr>
        <td><a href="#"></td>
    </tr>
</table>

When I click on <a> I want to add new <tr> next to <tr> of which <a> is clicked.

So the result will be:

<table>
    <tr>
        <td><a href="#"></td>
    </tr>
    <tr>
        <td><a href="#"></td>
    </tr>
</table>
like image 245
Bharat Patil Avatar asked Aug 30 '10 11:08

Bharat Patil


2 Answers

Example:

$('a').bind('click', function(){
  $('<tr><td>new td</td></tr>').insertAfter($(this).closest('tr'));
});

If you want to create a clone use:

$('a').live('click', function(){
  var $this     = $(this),
      $parentTR = $this.closest('tr');

  $parentTR.clone().insertAfter($parentTR);
});

Example link: http://www.jsfiddle.net/7A6MQ/

Basically, you create a copy from the tr element (which includes child nodes) and insert that copy after that element. Therefore, you need the .live binding to make sure that newly created a elements do also invoke that click handler.

Ref.: .clone(), .insertAfter(), .live()

like image 118
jAndy Avatar answered Oct 16 '22 19:10

jAndy


Also, you can write:

$('a').bind('click', function () {
    $(this).closest('tr').after('<tr><td>new td<td></tr>');
});

Not so much difference but looks more readable.

like image 43
Rock'n'muse Avatar answered Oct 16 '22 19:10

Rock'n'muse