Search code examples
jqueryhtmlhtml-tableappendcell

Append a cell in a HTML table using JQuery


I have a table in my web page, just this code:

<table id = "grid" >
</table>

Also, this button to add three columns in one row (the elements are a: text area, a droppable area and a button).

<button class = "plus"> + </button>

this function is run when the button is clicked:

$( ".plus" ).button().click(function() {
   $('<tr></tr>').appendTo("#grid");
   $('<td><textarea/></td>').appendTo("#grid tr:last"); 
   $('<td id = "regla"></td>').droppable( drpOptions ).appendTo("#grid tr:last");
   $('<td><button class = "addRow"> + </button></td>').appendTo("#grid tr:last");
});

This runs smoothly, up to this point all good. The thing I can't make is that when the button I'm appending (class="addRow") is clicked the button is removed and the same set of three items (text area, droppable and the button) is append to the row. I want that this new button appended do the same thing.

I think that the code is going to look like this:

$(".addRow").button().click(function(){
  var myColumn = $(this).closest("td").prevAll("td").length;
  var myRow = $(this).closest("tr").prevAll("tr").length;
  $("#grid").rows[myRow].cells[myColumn].append('<td><textarea/></td>');
});

or like this:

$(this).parents("table").find("tr:eq("+myRow+")")(function(){
 $(this).find("td:eq("+myColumn+")").append('<td><textarea/></td>');
});

Can you help me make it right or do it the right way?


Solution

  • I just came across trying to do this myself and ended up with an equivalent to this:

    $( ".plus" ).button().click(function() {
       addRow();
    });
    
    function addRow() {
       var newRow = $('<tr></tr>').appendTo($('#grid'));
       addRowContents(newRow);
    }
    
    function addRowAfter(target) {
      var newRow = $('<tr></tr>');
      addRowContents(newRow);
      target.after(newRow);
    }
    
    function addRowContents(row) {
     $('<td><textarea/></td>').appendTo(row); 
       $('<td id = "regla"></td>').droppable( drpOptions ).appendTo(row);
      var buttonCell = $('<td></td>').appendTo(row);
      $('<button></button>').addClass('addRow').text('+').click(function(){
        addRowAfter($(this).closest('tr'));
        $(this).hide();
      }).appendTo(buttonCell); 
    }
    

    I believe this is what you were after, the plus button adds a new row to the end of the table, and the button on each row adds a new row directly after that row, and then hides the button. If you paste that code into your fiddle it should work.

    Bit late but thought I'd post just in case it helps :)