Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element's parent row

I have a table with buttons in cells, like so:

<table>
    <tr>
        <td>information</td>
        <td>
            <button onclick="function(id, this)">Text</button>
        </td>
    </tr>
</table>

The function called when the button is pressed does some ajax stuff, and if it's successful, the whole row where the button is should be removed from the DOM. (It's a delete function ;)

However, I can't seem to get jQuery to remove the correct row. I've used $('#id').parent().parent().remove();, as I thought it would go: button -> cell -> row, but it just removes the first row of the table?! Wherever did I lose? :(

like image 274
Fireworm Avatar asked Nov 23 '25 08:11

Fireworm


2 Answers

http://jsfiddle.net/ZnX5J/

<table>
    <tr>
        <td>information</td>
        <td>
            <button onclick="removeRow(this)">Text</button>
        </td>
    </tr>
    <tr>
        <td>blah</td>
        <td>
            <button onclick="removeRow(this)">Text</button>
        </td>
    </tr>
</table>

JavaScript

removeRow = function(el) {
    $(el).parents("tr").remove()       
}
like image 180
MDEV Avatar answered Nov 25 '25 21:11

MDEV


.closest() can do that easily -

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

You can remove inline onClick and handle the click like this -

$('button').on('click',function(){
   $(this).closest('tr').remove();
});

Demo ------> http://jsfiddle.net/2nJYe/

like image 20
Mohammad Adil Avatar answered Nov 25 '25 23:11

Mohammad Adil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!