code in initComplete is ignored if I search in datatable
code in initComplete is ignored if I search in datatable
bejbe01
Posts: 10Questions: 4Answers: 0
I have implemented simple datatable where I generate column with some class and in initComplete I create simple onclick action on this class. This works fine until I do search in table, or change row number of table. Then my click on button is completely ignored.
Any clue what might be wrong?
var tableready = function() {
commtable= $('#communication').DataTable({
'order': [4, 'desc'],
'serverSide': true,
'ajax': '/communications.json',
'stateSave' :true,
columns: [
{data: 'subject_name_show'},
{data: 'person_first_name' },
{data: 'about' },
{data: 'keyword' },
{data: 'created_at','render' : function(data,type,row) {
return prettyDate(row.created_at);
} },
{data: 'user_name' },
{
"className": 'commedit-control',
"orderable": false,
"data": null,
"defaultContent": '<a><center><i class="fa fa-pencil-square-o fa-2x" aria-hidden="true"></i></center></a>'
},
{data: 'delete_communication', orderable: false, searchable: false}
],
'dom': 'lfr<"pull-right"B>tip',
initComplete: function() {
$('.commedit-control').on('click',function(event){
alert("hello");
});
}
});
};
$(".communication.index").ready(tableready);
document.addEventListener('turbolinks:before-cache', function() {
if ($('#communication_wrapper').length ==1) {commtable.destroy() ;}
});
$(".communication.index").on('turbolinks:load', tableready);
This discussion has been closed.
Answers
ok after few hours I found out that instead of puting function into initComplete I have to put it into drawCallback
You might be better off using delegated events:
https://datatables.net/faqs/index#events
Otherwise, unless you turn off the click event first, each on event will append to the click events for that selector. In other words you could end up with the click event firing multiple times.
Something like this should work:
$('#communication tbody').on('click', 'td.commedit-control', function ()
You can even move it outside of init complete.
Kevin