lookininward lookininward - 2 months ago 8
HTML Question

How can I delete selected <tr>(parent) div every time a button (child) is clicked in jQuery?

HTML:

<tr>
<td>
<div class="input">
<p>Room 1: </p>
</div>
</td>
<td>
<div class="revenue-input">
<input type="number" min="0" id="room1rev" size="1" placeholder="0">
</div>
</td>
<td>
<button id="btn-del-rev" class="btn-del">-</button>
</td>
</tr>
<tr>
<td>
<div class="input">
<p>Room 2: </p>
</div>
</td>
<td >
<div class="revenue-input">
<input type="number" min="0" id="room2rev" size="1" placeholder="0">
</div>
</td>
<td>
<button id="btn-del-rev" class="btn-del">-</button>
</td>
</tr>


jQuery:

<!-- Delete Element -->
<script>
$(document).ready(function() {
$("#btn-del-rev").click(function() {
$(this).parent().parent().remove()
});
});
</script>


When the button with the #btn-del-rev id is clicked it removes the entire tr structure (parent, etc.) However, clicking the same button on the next row doesn't remove the next tr.

I understand that it's a problem with reusing an id, but I'm having a hard time figuring out how to have the button work across all tr that I want deleted without creating a unique id, and redundant jQuery code.

Any help is appreciated!

Answer

An ID must be unique !

Change or remove the ID attribute in your HTML

<button class="btn-del">-</button>

And use the .class attribute instead

$(".btn-del").click(function() {

By the way, instead of .parent().parent(), you should use .closest()

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

get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

jQuery Closest documentation