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
</td>
</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?
Remove table column using jQuery. To remove a column, it is not ideal to assign a delete button like we did for removing rows. Instead, the column will be removed when the column header is clicked. In the jQuery code, we need to attach a click event to the table header.
The jQuery remove() method is used to remove a row from HTML table. jQuery remove() Method: This method removes the selected elements alongwith text and child nodes. This method also removes data and events of the selected elements.
Get the column index in a variable (Column that we want to remove). Delete each cell by . deleteCell(i) method(where, i is the column index) by traversing the each row of the table.
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 ]);
});
});
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With