A few jQuery helpers for working with HTML tables. Adding, removing rows and columns.
/*
Remove the last/bottom table row
http://jquery-howto.blogspot.com/2009/05/remove-bottom-table-row-using-jquery.html
*/
function removeTableRow(jQtable) {
jQtable.each(function () {
if ($('tbody', this).length > 0) {
$('tbody tr:last', this).remove();
} else {
$('tr:last', this).remove();
}
});
}
// Here is how to use it
removeTableRow($('table'));
/*
Remove n'th table column - jQuery plugin
http://jquery-howto.blogspot.com/2009/05/remove-nth-table-column-jquery-plugin.html
*/
$.fn.removeCol = function (col) {
// Make sure col has value
if (!col) {
col = 1;
}
$('tr td:nth-child(' + col + '), tr th:nth-child(' + col + ')', this).remove();
return this;
};
/*
Add a new table row to the bottom of the table
http://jquery-howto.blogspot.com/2009/02/add-table-row-using-jquery-and.html
*/
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);
}
});
}
addTableRow($('#myTable'));
addTableRow($('.myTables'));
/*
Remove table row on user click
http://jquery-howto.blogspot.com/2009/05/remove-table-row-on-user-click.html
*/
/*
<table>
<tr>
<td>row 1, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
</table>
*/
$('table td img.delete').click(function () {
$(this).parent().parent().remove();
});
/*
Dynamically adding table row count number using JavaScript and jQuery
http://jquery-howto.blogspot.com/2009/01/dynamically-adding-table-row-count.html
*/
(function ($) {
$.fn.extend({
addCount: function () {
return $(this).each(function () {
if ($(this).is('table')) {
$('thead th:first, thead td:first', this).each(function () {
if ($(this).is('td')) {
$(this).before('<td rowspan="' + $('thead tr').length + '">#</td>');
} else if ($(this).is('th')) {
$(this).before('<th rowspan="' + $('thead tr').length + '">#</th>');
}
});
$('tbody td:first-child', this).each(function (i) {
$(this).before('<td>' + (i + 1) + '</td>');
});
}
});
}
});
})(jQuery);
// To apply it to your tables use this code:
$('table').addCount();
$('.some-table-class').addCount();
$('#some-table-id').addCount();