Reputation: 470
I want to remove a row from a datatable table with an on click event. I got this based on the documentation and my code works. However I don't want to hard code the variable name for my datatable object in the remove function as there might be multiple or differently called datatables. How can I determine the correct object where the row should be removed?
Updated code in codepen https://codepen.io/bintux/pen/QWLKxQG based on @David Hedlund's answer.
var table = $('#example').DataTable();
$('.deleterow').on('click', function () {
//I want to avoid this hard coded name for the datatable object but instead get the right object when the user clicks in the table
table
.row($(this).parents('tr'))
.remove()
.draw();
});
var table = $('#example').DataTable();
$('.deleterow').on('click', function() {
table
.row($(this)
.parents('tr'))
.remove()
.draw();
//console.log(row);
});
<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.18/js/dataTables.bootstrap4.min.js"></script>
<div class="container">
<table id="example" class="display nowrap" width="100%">
<thead>
<tr>
<th>Remove</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Remove</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td><span class="deleterow">X</span></td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$3,120</td>
</tr>
<tr>
<td><span class="deleterow">X</span></td>
<td>Garrett Winters</td>
<td>Director</td>
<td>Edinburgh</td>
<td>63</td>
<td>2011/07/25</td>
<td>$5,300</td>
</tr>
<tr>
<td><span class="deleterow">X</span></td>
<td>Donna Snider</td>
<td>System Architect</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$3,120</td>
</tr>
</tbody>
</table>
</div>
Upvotes: 0
Views: 274
Reputation: 129792
.deleterow
will always be a child of the table of interest.
Inside your click listener, you could access it like so:
var table = $(this).closest('table').DataTable();
Upvotes: 1