Reputation: 8727
On this page
You can see that the following codes attach a click
handler to the tbody
to implement the row selection feature before the actual datatable object is inited:
$("#example tbody").click(function(event) {
$(oTable.fnSettings().aoData).each(function (){
$(this.nTr).removeClass('row_selected');
});
$(event.target.parentNode).addClass('row_selected');
});
/* Init the table */
oTable = $('#example').dataTable();
Since I need this feature for all datatables in my project, I would like these codes to run automatically on every datatable object initialization.
I have found a possible place here (which is the fnInitComplete
event) where these codes can be added:
However, the codes should run by default, rather than like the example, passing them to the fnInitComplete
event in the option object.
How do you think this can be done?
Many thanks to you all.
EDIT:
In the end, I have decided to define a global table option object, and I clone it and modify it if necessary before using it to init the dataTable like this:
//default table options defined globally, you can namespace it if you like
var jqDataTablesDefaultOptions:{
"fnDrawCallback": function (oSettings, json) {
var nTrs = this.fnGetNodes();
$(nTrs).click(
function(){
$(nTrs).removeClass('row_selected');
$(this).addClass('row_selected');
}
);
},
"aLengthMenu": [5,10,15,20,100],
"iDisplayLength":5,
"oLanguage": {
"sUrl": "/assets/lib/DataTables-1.8.2/media/language/zh_TW.txt"
},
"bJQueryUI": true
"sPaginationType":"full_numbers"
};
On every page that I use datatable, I will have the following codes:
//copy the default options
var tableOptions=$.extend(true,{},jqDataTablesDefaultOptions);
//modify the options if necessary
tableOptions.iDisplayLength=10;
//init the datatable
$('#example').dataTable(tableOptions);
Please feel free to read this page for the reason I use fnDrawCallback
rather than fnInitComplete
.
Upvotes: 0
Views: 1090
Reputation: 2006
I would make my own plugin and employ jQuery $.extend function to extend options you set with defaults you want. If you don't want to bother making plugin for this, you may use a DataTools plugin.
Another option to go is edit DataTable js file - search for "classSettings" in the code. But obviously this has big disadvantage that if you want to upgrade to new version, you have to edit it again.
And for this kind of stuff I would rather use fnRowCallback as it has table tr doom element as an argument to which you may bind any event you want. But you have to wrap it to jQuery if you want to use any jQuery functionality.
Upvotes: 1