Reputation: 3358
I'm new to Datatables. I'm not sure how to get the row index when the button in a row is clicked. I get undefined object error. Can anyone guide me how to get the row index?
Below is the Code I have tried till now:
var table = $('#subcategoryDatatable');
var url = $('#url').val();
var tableObj = table.DataTable( {
"processing": true,
"serverSide": false,
"aoColumnDefs": [
{ "bSearchable": true, "aTargets": [ 0 ] },
],
ajax:
{
url: url,
dataSrc: 'data',
type: 'GET'
},
columns: [
{ data: 'id'},
{ data: 'subcategory'},
{ data: 'category'},
/* DELETE */ {
mRender: function (data, type, row) {
return '<a href="#" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#myModal">DELETE</a>'
}
}
],
} );
$("#cancel").click(function()
{
$('#myModal').modal('hide');
});
$("#delete").click(function(){
var target_row = $(this).closest('tr').get(0);
alert('Delete this id '+target_row);
});
Upvotes: 1
Views: 4095
Reputation: 1354
try this :
mRender: function (data, type, row) {
return '<a href="#" id="rowid' + row.id + '" class="btn btn-danger btn-xs" data-toggle="modal" onclick="DeleteRecordModal('+ row.id +')">DELETE</a>'
}
and when you click on delete button open a modal :
function DeleteRecordModal(id) {
$("#myModal").modal("show");
$("#myModal").attr("data-id",id);
}
and then click on delete button on modal
$("#delete").click(function(){
var getid = $("#myModal").attr("data-id");
$("#rowid" + getid).closest("tr").remove();
});
Upvotes: 1
Reputation: 1381
var url = $('#url').val();
var tableObj = $('#subcategoryDatatable').DataTable( {
"processing": true,
"serverSide": false,
"aoColumnDefs": [
{ "bSearchable": true, "aTargets": [ 0 ] },
],
ajax:
{
url: url,
dataSrc: 'data',
type: 'GET'
},
columns: [
{ data: 'id'},
{ data: 'subcategory'},
{ data: 'category'},
{
data: null,
orderable: false,
className: "dt-center",
defaultContent:'<a href="#" class="remove" id=del>Delete</a>'
}
],
} );
$('#subcategoryDatatabletbody ').on('click', 'tr td #del', function () {
var row = $(this).parents('tr')[0];
var mydata = (tableObj .row(row).data());
alert(mydata["Id"]);
var con=confirm("Are you sure you want to delete this Category"+mydata["category"]);
if(con)
{
// Delete category Code
}
else
{
}
});
Make Sure All of this code should be inside document.ready
function
Upvotes: 0