Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery delete table column

Tags:

jquery

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?

like image 807
eba Avatar asked Dec 28 '10 06:12

eba


People also ask

How can delete column in jQuery?

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.

How to remove data from table in jQuery?

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.

How do you delete a column in HTML?

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.


2 Answers

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 ]);
    });
});
like image 83
user113716 Avatar answered Oct 23 '22 04:10

user113716


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();
like image 43
Amay Kulkarni Avatar answered Oct 23 '22 05:10

Amay Kulkarni