Question

I have an HTML table with one TH row and several TRs that are added dynamically. Each TR has a button in the last column.

What do I need so that by click on the button the closest TR gets removed from the table? I tried using $(this).closest.remove() but this didn't work so I assume I need to add IDs or something else here.

A basic example table would look like the following:

<table class='tableClass'>
    <tbody>
        <th>
            <td>Text</td><td>Text</td><td>Text</td>
        </th>
        <tr>
            <td>Text</td><td>Text</td><td><button type='button' class='btnClass'>Delete</button></td>
        </tr>
        <tr>
            <td>Text</td><td>Text</td><td><button type='button' class='btnClass'>Delete</button></td>
        </tr>
        <tr>
            <td>Text</td><td>Text</td><td><button type='button' class='btnClass'>Delete</button></td>
        </tr>
    </tbody>
</table>
Was it helpful?

Solution

You need to give the closest function a selector. Try this:

$('.btnClass').click(function() {
    $(this).closest('tr').remove();
});

Also, your HTML is invalid as th should be a child of tr:

<table class='tableClass'>
    <tbody>
        <tr>
            <th>Text</th>
            <th>Text</th>
            <th>Text</th>
        </tr>
        <tr>
            <td>Text</td>
            <td>Text</td>
            <td>
                <button type='button' class='btnClass'>Delete</button>
            </td>
        </tr>
        <tr>
            <td>Text</td>
            <td>Text</td>
            <td>
                <button type='button' class='btnClass'>Delete</button>
            </td>
        </tr>
        <tr>
            <td>Text</td>
            <td>Text</td>
            <td>
                <button type='button' class='btnClass'>Delete</button>
            </td>
        </tr>
    </tbody>
</table>

Example fiddle

OTHER TIPS

You can do this using .closest( selector ) properly like:

$(this).closest('tr').remove();

Actually in your code:

$(this).closest.remove()
            ___^___

you are missing both the opening and closing parenthesis () and the selector tr.

http://jsfiddle.net/cpvh9/

$(".btnClass").click(function(){
        $(this).parents('tr').remove();
    });

From your HTML code it looks like you want to remove parent TR, try this

$(".btnClass").click(function(){
    $(this).parents("tr:first").remove();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top