Friday, February 20, 2009

Add table row using jQuery and JavaScript

I noticed that there are a lot of developers who need to dynamically add a new table row to the bottom of their tables. I wrote a little javascript function that takes your jQuery selection of tables and dynamically adds a table row at the bottom of them.

jQuery add table row function definition:

/*
    Add a new table row to the bottom of the table
*/

function addTableRow(jQtable){
    jQtable.each(function(){
        var $table = $(this);
        // Number of td's in the last table row
        var n = $('tr:last td', this).length;
        var tds = '<tr>';
        for(var i = 0; i < n; i++){
            tds += '<td>&nbsp;</td>';
        }
        tds += '</tr>';
        if($('tbody', this).length > 0){
            $('tbody', this).append(tds);
        }else {
            $(this).append(tds);
        }
    });
}

jQuery add table row function usage example:

addTableRow($('#myTable'));
addTableRow($('.myTables'));

14 comments:

  1. I think it might be simpler to do this:

    $('.somebutton').click(function(){
    $('#myTable tbody>tr:last').clone(true).insertAfter('#myTable tbody>tr:last');
    });

    ReplyDelete
  2. +1 for Ryan's solution

    ReplyDelete
  3. Amazing Ryan, it works perfectly.

    ReplyDelete
  4. totally uselles function because we cant add some content!

    ReplyDelete
  5. Ryan can u xplain me ?

    ReplyDelete
  6. idem +1 for RYan solution ;)

    ReplyDelete
  7. I simply use this:

    $('#' + tableName + ' tbody').append(rowHtml);

    ReplyDelete
  8. excellent solution Ryan .. Anyway, there should be a problem with clone: what about if your table contains an input text id? Your method will clone ids, won't it?

    ReplyDelete
  9. or to do this: vey similar to Ryan solution
    $(jQtable).find('tbody').append($(jQtable).find('tbody>tr:last').clone(true));

    ReplyDelete
  10. maybe put the cloned result in a viariable and then empty the input's
    clonedResults = find($('#myTable tr:last')).clone();
    clonedResults.find('input').val('');

    theTable = $('#myTable').find('tbody');
    clonedResults.appendTo(theTable);

    ReplyDelete
  11. as you know.. using a clone will also copy whatever values inside the tr.. i think the original post was great.

    ReplyDelete
  12. There is one downside to Ryan's solution. If there is content in the last row of the table, that too is copied.

    ReplyDelete