tags:

views:

61

answers:

1

Hello, I have following table structure. (Using jQuery)

<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>
+2  A: 

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()

jAndy
jAndy - You don't need `.live()` for your second example. Just do `.clone(true)`, and it clones all associated data as well. http://www.jsfiddle.net/7A6MQ/1/
patrick dw