Remove Row
HTML for button (change 'myTable' for your actual table ID)
<input id="removeRowBtn" onclick="deleteRow('myTable')" value="Remove selected row" name="removeRowBtn" type="button">
Javascript (with an extra fadeOut effect)
var deleteRow = function(tableID) {
var ID = "#" + tableID;
var rowCount = jQuery(ID + " tbody tr").length;
jQuery(ID + " input:checked").each(function() {
if (rowCount > 1)
{
jQuery(this).closest('tr').fadeOut(function () {
jQuery(this).remove();
});
rowCount--;
}
else
alert("Cannot remove all rows.");
});
return false;
}
Add/duplicate Row (extra, not an answer)
HTML for button (change 'myTable' for your actual table ID)
<input id="addRowBtn" onclick="addRow('myTable')" value="Add row" name="addRowBtn" type="button">
Javascript (duplicates first row, with an fadeIn effect)
var addRow = function(tableID) {
var ID = "#" + tableID;
var rowCount = jQuery(ID + " tbody tr").length;
if (rowCount < 5) { // limit the user from creating more rows
jQuery(ID + " tbody tr:first").clone().appendTo(ID).hide().fadeIn();
} else {
alert("Cannot add more than 5 rows.");
}
return false;
}
Note: I use jQuery instead of $ because of possible conflicts. The code assumes your rows are within a tbody as well, to follow HTML5 standards and to avoid possible conflicts with a thead or tfoot. I also know it might be cleaner to use click event instead of html attribute onclick, but this has it's pros as well. Might help someone at least.