Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables 1.10 column count

I want to add an additional <thead> that will contain my filters for that column in datatable.

I am able to do that using the following script. (For this to work I should have thead defined in dom)

var tableid = $('#dataTableBuilder');
num_columns = tableid.find('thead > tr:first > th').length;
tableid.find('thead > tr:first').before('<tr id="filter-row"></tr>');
var filterrow = tableid.find('#filter-row');

while (num_columns-- > 0) filterrow.append('<th></th>');

Problem is I do not want to look at DOM to figure out number of columns to add those many <th>. (Reason for this is I am using Yajra Datatables HtmlBuilder to generate my table and I do not know number of columns upfront and the table code that this adds is only <table id='xxxxxx'></table>)

I hope the question is understood, I just need to know how can I get count of number of columns using datatables.

I tried myDataTable.fnSettings().aoColumns.length but it says "fnSettings is not a function" it looks like it is depricatedin 1.10, is there any alternative to this?

like image 578
karmendra Avatar asked Mar 14 '23 17:03

karmendra


1 Answers

Using the 1.10.x API there is multiple ways to get the number of columns. Examples :

var colCount = table.columns().header().length;
var colCount = table.row(0).data().length;
var colCount = table.columns()[0].length;
...

Regarding myDataTable.fnSettings().aoColumns.length I believe you are thinking of

table.init().columns / table.init().aoColumns etc

But table.init() only hold initialization options you actually have passed to dataTables. If you have a dataTables initialisation like this

var table = $("#example").DataTable({
   columnDefs : [
     { targets : [0], sortable : false }
   ]
})

then table.init().columnDefs and table.init().aoColumnDefs will be present, but table.init().columns will not, since you have not passed a columns struct to dataTables.

like image 84
davidkonrad Avatar answered Mar 16 '23 06:03

davidkonrad