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.
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.
Click the object, then press Alt + P . This opens the Clear Parent menu. Select Clear and Keep Transformation .
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? 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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With