Reputation: 45
I've this type of table:
<tr>
<td>
<input type="number">
</td>
<td>
<button type="button" data-action="remove-item">
<i class="fa fa-trash"></i>
</button>
</td>
</tr>
By clicking on the 'remove-item', I want to remove the current <tr>
.
Here what I've tried:
$('[data-action="remove-item"]').click(function(){
$(this).closest('td').closest('tr').remove();
})
But sometimes it doesn't work.
Why ?
Thanks.
Upvotes: 0
Views: 125
Reputation: 10198
Try this
$("#YourTableId").on('click','[data-action="remove-item"]',function(){
$(this).closest('tr').remove();
});
Upvotes: 0
Reputation: 1572
.closest()
function will find the element that you want to remove. So you don't need to use it twice.
Jquery.com says below about the .closest()
function.
Travels up the DOM tree until it finds a match for the supplied selector
$('[data-action="remove-item"]').click(function(){
$(this).closest('tr').remove();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="number"> 1
</td>
<td>
<button type="button" data-action="remove-item">
remove
</button>
</td>
</tr>
<tr>
<td>
<input type="number"> 2
</td>
<td>
<button type="button" data-action="remove-item">
remove
</button>
</td>
</tr>
<tr>
<td>
<input type="number"> 3
</td>
<td>
<button type="button" data-action="remove-item">
remove
</button>
</td>
</tr>
</table>
Upvotes: 1