I have Edit and Delete buttons in my jQuery DataTable. The first column is a record ID column and is hidden. I have event handlers for the Edit and Delete buttons. Should I rather use the event handler for the DataTable click and tr function to get the id, or if using the button event handlers (preferable), how can I get the Id from the row? i.e. identify which row was clicked on?
const dataTable = $('#personTable').DataTable({
data: serializedObject,
columns: [
{ data: 'ID', 'visible': false},
{ data: 'TitleCode' },
{ data: 'TitleDetail' },
{ data: 'FirstName' },
{ data: 'LastName' },
{data: null}
],
columnDefs: [
{
targets: 8,
data: 'ID', //'<div class="btn-group" style="width:70px"> <button type="button"' +
defaultContent: '<div class="floatRightClass" >' +
'<a class="btn btn-default glyphicon glyphicon-pencil btn-edit" title="Edit"> </a>' +
'<a class="btn btn-default glyphicon glyphicon-trash btn-delete" title="Delete"> </a>' +
'</div>'
},
]
});
$(".btn-delete").click(function (e)
{
var dtTable = $('#personTable').DataTable();
var selectedRows = dtTable.rows('tr.selected');
var id = selectedRows.data().toArray().map(function (row) { return row.id });
console.log("id= " + ID);
// or
console.log("id= " + dataTable.rows('tr.selected').data().toArray().map(function(row){return row.ID}));
// This works, but the row index is hardcoded
alert("..." + dtTable.cells({ row: 0, column: 0 }).data()[0]);
// Error: undefined
selectedIndex = dtTable.row(this).data()[0];
alert("Id = " + selectedIndex.ID);
});
$('#personTable tbody').on('click', '.btn-delete', function ()
{
var tr = $(this).closest("tr");
var rowindex = tr.index();
alert("rowindex " + rowindex);
// Get the value of the ID in the hidden column (col: 0)
alert("..." + dataTable.cells({ row: rowindex, column: 0 }).data()[0]);
});
By using the
$('#personTable tbody').on('click', '.btn-edit2', function ()
I can get the index of the row and the hidden cell value orID for use in serverSide - Db - Processing.I would suggest the following approach.
Essential part here is to use
rows().remove()
method (you don't need to have id's of the records you would like to delete).However, if you wish to delete those records from your backend storage as well, you might do something like: