Unable to remove table row using jQuery
37 1 year ago
I want to remove table row, data is deleted from database but why it is not removed from html table. Any solution appreciated!
$('#datatables').on('click', '.delete_department', (e) => {
var id = e.currentTarget.id;
$.ajax({
type: 'POST',
url: BASE_URL + 'admin/delete_department',
data: { id: id },
success: (response) => {
$('#datatables').closest('tr').remove();
}
});
});
Here is the HTML Table that is generated using PHP
<table id="datatables" class="css-serial text-center table table-striped table-no-bordered table-hover dataTable dtr-inline">
<thead>
<tr role="row">
<th>#</th>
<th>Department</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th rowspan="1" colspan="1">#</th>
<th rowspan="1" colspan="1">Department</th>
<th rowspan="1" colspan="1">Action</th>
</tr>
</tfoot>
<tbody>
<?php foreach ($departments as $key => $department) { ?>
<tr>
<td>
<p data-letters="<?php echo ucwords(substr($department['department'], 0, 1)); ?>"></p>
</td>
<td><?php echo $department['department'] ?></td>
<td>
<button class='edit_department btn btn-danger btn-link' id='<?php echo $department['id'] ?>'><i class='material-icons'>edit</i></button>
<button class='delete_department btn btn-danger btn-link' id='<?php echo $department['id'] ?>'><i class='material-icons'>close</i></button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
Answers { 1 }
1 year ago
Save the reference of clicked button element and then use closest
to get tr
.
$('#datatables').on('click', '.delete_department', function(e) {
const that = $(this);
var id = e.currentTarget.id;
$.ajax({
type: 'POST',
url: BASE_URL + 'admin/delete_department',
data: { id: id }, // or just use shorthand notation { id }
success: (response) => {
$(that).closest('tr').remove();
}
});
});
Note - Instead of arrow function, use function()
to get the reference of clicked element.
Related Question
Hot Question