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> </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'));
I think it might be simpler to do this:
ReplyDelete$('.somebutton').click(function(){
$('#myTable tbody>tr:last').clone(true).insertAfter('#myTable tbody>tr:last');
});
+1 for Ryan's solution
ReplyDeleteAmazing Ryan, it works perfectly.
ReplyDeletetotally uselles function because we cant add some content!
ReplyDeletegreat
ReplyDeleteRyan can u xplain me ?
ReplyDeleteidem +1 for RYan solution ;)
ReplyDeleteI simply use this:
ReplyDelete$('#' + tableName + ' tbody').append(rowHtml);
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+1 for Ryan
ReplyDeleteor to do this: vey similar to Ryan solution
ReplyDelete$(jQtable).find('tbody').append($(jQtable).find('tbody>tr:last').clone(true));
maybe put the cloned result in a viariable and then empty the input's
ReplyDeleteclonedResults = find($('#myTable tr:last')).clone();
clonedResults.find('input').val('');
theTable = $('#myTable').find('tbody');
clonedResults.appendTo(theTable);
as you know.. using a clone will also copy whatever values inside the tr.. i think the original post was great.
ReplyDeleteThere is one downside to Ryan's solution. If there is content in the last row of the table, that too is copied.
ReplyDelete