jQuery delete table column
I have a table and cannot change markup:
<table>
<thead>
<tr>
<th>
blablabla
</th>
<th>
blablabla
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
efgd
</td>
<td>
efghdh
</t开发者_Go百科d>
</tr>
</tbody>
</table>
Here is my function, which should delete a column. It is called on cell click:
function (menuItem, menu) {
var colnum = $(this).prevAll("td").length;
$(this).closest('table').find('thead tr th:eq('+colnum+')').remove();
$(this).closest("table").find('tbody tr td:eq('+colnum+')').remove();
return;
}
But it deletes something else, not the column I wanted to delete. Where am I wrong?
A column is pretty much just cells, so you'll need to manually loop through all the rows and remove the cell by the index.
This should give you a good starting point for removing the 3rd column:
$("tr").each(function() {
$(this).children("td:eq(2)").remove();
});
This uses .delegate()
for the handler, and a more native approach using cellIndex
to get the cell index that was clicked, and cells
to pull the cell from each row.
Example: http://jsfiddle.net/zZDKg/1/
$('table').delegate('td,th', 'click', function() {
var index = this.cellIndex;
$(this).closest('table').find('tr').each(function() {
this.removeChild(this.cells[ index ]);
});
});
This works fine for me:
$(".tableClassName tbody tr").each(function() {
$(this).find("td:eq(3)").remove();
});
If you have the static html (consider table with 10 columns),
then remove the first column along with header using below:
$('#table th:nth-child(1),#table td:nth-child(1)').remove();
now the new table will have 9 columns , now you can remove any column using the number:
$('#table th:nth-child(7),#table td:nth-child(7)').remove();
Remove the first column from each row.
$('.mytable').find("tr td:nth-child(1)").each(function(){
$(this).remove()
});
By Applying some class on targeted column we can remove it. For example
<tr>
<td>ID</td>
<td>Name</td>
<td><button class="btnRemoveMember">X</button></td>
</tr>
From above example table we can remove 3rd column of table as follow.
$(.btnRemoveMember).closest('td').remove();
精彩评论