Get Creative With Data Tables: Row Click Events
Introduction
Datatables from datatables.net are so lovely, especially with the responsive extension that you can enable by including dataTables.responsive.js in your project. I particularly find fascinating the combination of search / filtering, pagination, ordering and exporting features which are available right 'out-of-the-box'.
Issue
Well, as great as datatables are, you will find it difficult if not impossible to develop a system with acceptable user-experience using bare-bone datatables implementation. In my own case, because I was porting my superb Asset and Inventory Management Application found at asset.bz to the mobile platforms using PhoneGap, I needed the user to be able to tap on any record in order to perform some pre-define operations like editing, approvals etc.
Solution
Apparently, the solution isn't far fetched. The sample code below would do the job nicely:
// HTMLTableData is your array of records to be displayed in the data table
var HTMLTableData = [];
//our objective in the for-loop below is to include another property (DT_RowId)
//the datatables plugin will use this property as the 'id' property for each of our rows
for (var i = 0; i < HTMLTableData.length; i++) {
HTMLTableData[i].DT_RowId = HTMLTableData[i].Id;
}
var HTMLTableName = "my-table-id";
var cols = []; // in order to understand the usage of 'cols' please read this other post
DataTableObject = $('#' + HTMLTableName).DataTable({
data: HTMLTableData, columns: cols
});
$('#' + HTMLTableName + ' tbody').on('click', 'td', function () {
var tr = $(this).parents('tr');
var row = DataTableObject.row(tr);
DataTable_Record_Id = tr[0].id;
RowClickMethod(tr[0].id); //call the function you wish to trigger here.
});
var RowClickMethod = function(id){
//do some stuff
}
Comments
Post a Comment