user2571510
user2571510

Reputation: 11377

jQuery: what is needed to remove closest with click on button

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>

Upvotes: 1

Views: 1916

Answers (4)

Kalpesh Fulpagare
Kalpesh Fulpagare

Reputation: 1299

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

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

Upvotes: 1

Pradeep shyam
Pradeep shyam

Reputation: 1292

http://jsfiddle.net/cpvh9/

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

Upvotes: 1

palaѕн
palaѕн

Reputation: 73916

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.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337620

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

Upvotes: 2

Related Questions