I'm adding the <tr>
via a Javascript var:
var txtBox = "<tr id='dynTR'><td><input type='text' class='textBoxes' /></td><td><input type='text' class='textBoxes' value='0' /></td><td><input type='button' value='-' /></td></tr>";
With my function being:
function AddTR(table) {
$(table).append(txtBox);
}
My table structure (along with the button for the function) in the HTML being:
<table id="tblTest" class="testTable">
<thead>
<tr>
<td>Product</td>
<td>Quantity</td>
<td>Remove TR</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<br />
<input type="Button" id="btnTest" value="Add Table Row" onclick="AddTR($('#tblTest'))" />
So how do I go about using the .remove()
function in jQuery to get rid of the parent tag without accidentally removing all <tr id='dynTR'>
tags?
Considering this one is the remove button:
<input type='button' value='-' />
The following will do:
$('#tblTest input[type="button"]').click(function () {
$(this).closest('tr').remove();
});
I'd suggest you use jQuery event handlers instead of using inline onclick
and friends. $(this)
is the jQuery object of the button that was clicked, .closest()
will look in the parents of the button and find the first tr
, then remove it.
The best way would be to change the HTML for your remove button:
<input type='button' value='-' class='removeButton' />
so you can target your remove button like this:
$('#tblTest .removeButton').click(...
This is better because with the previous example, every possible input type="button"
in the table would get the event, even though we just need it on these special ones (not a problem if there are no other buttons in the table).