Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a parent tr

UPDATE 1:

I'm wondering if it has anything to do with the button being within the element which is being deleted, so it would end up deleting the button which does the deleting too? That might not be the problem, I was just typing that I'm thinking.

I've just tried:

$( "input.btnX" ).click(function(event) {
    alert("test");
});

and I don't get an alert... Should I be using live or is it on now because the buttons along with the table are dynamically generated.

ORIGINAL QUESTION:

I have a table (dynamically generated, so I won't know how many tr's it has in tbody which looks something like this:

<table>
    <tbody>
        <tr>
            <td>col1</td>
            <td>col2</td>
            <td><input type="button" class="btnX" name="x" value="x" /></td>
        </tr>
        <tr>
            <td>col1</td>
            <td>col2</td>
            <td><input type="button" class="btnX" name="x" value="x" /></td>
        </tr>
    </tbody>
</table>

How do I delete the parent tr if an x button is clicked? So in this example, if the bottom x is clicked, it should remove the bottom tr.

I've tried this:

$( "input.btnX" ).click(function(event) {
    $(this).parent('tr').remove();
});

But nothing happens.

like image 601
oshirowanen Avatar asked Aug 01 '12 09:08

oshirowanen


People also ask

How to remove parent tr 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 I remove parent object?

Click the object, then press Alt + P . This opens the Clear Parent menu. Select Clear and Keep Transformation .

How do I remove TR on click?

jQuery: Code to Remove Table Row (tr) on Button Click. Here, we make a jQuery click event on the button tag. Using the closest() method we select the current row ie closest tr of our delete button, and then with the remove() method will delete that record.

How do I get parent TR?

How do I get parent TR? Use closest() method to get the closest parent element matching the selector. closest() – Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.


1 Answers

Just use

    $( "input.btnX" ).click(function(event) {
    $(this).parent().parent().remove();
});

Or

  $( "input.btnX" ).click(function(event) {
        $(this).closest("tr").remove();
    });

As what you are doing is going to the parent which is the tr and then looking for a tr

See an example here http://jsfiddle.net/gYDUF/

If your table is beeing rendered by javascript you may also have to change your click on

$("input.btnX" ).live(click, function(){

     $(this).closest("tr").remove();
}); 
like image 178
Dominic Green Avatar answered Oct 02 '22 14:10

Dominic Green