Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name of datatable column?

Tags:

I'm using DataTable 1.10.9 (from https://datatables.net). Columns for the datatable are defined at the initialization step in javascript and each column has a unique name, e.g.:

var table = $('#example').DataTable({             columns: [                 { name: 'first-name' },                 { name: 'last-name' },                 { name: 'position' },                 { name: 'location' },                 { name: 'salary' }             ]         }); 

I know I can get the column from the table by the name I've given it, but I can't seem to find how to find a column's name from the column object. (I'm hoping it's possible with the current state of the component.) For example:

        table.columns().every(function() {             //I'd want to see what the name of this column is, something like:             console.log(this.name()); //will throw an exception since no such function exists             //or             console.log(this.name); //will output 'undefined'         }); 

What's the proper function or property to get the name there?

like image 710
Anna T Avatar asked Sep 16 '15 01:09

Anna T


2 Answers

You can retrieve the initialization options through table.settings().init() - and by that the columns definition this way :

var columns = table.settings().init().columns; 

When clicking on a cell / <td> you can find the column index by (best practice in case of hidden columns) :

var colIndex = table.cell(this).index().column; 

An example of a click handler that alerts the corresponding column.name when a cell is clicked

$("#example").on('click', 'td', function() {     //get the initialization options     var columns = table.settings().init().columns;     //get the index of the clicked cell     var colIndex = table.cell(this).index().column;     alert('you clicked on the column with the name '+columns[colIndex].name); }) 

Your every() example would be

var columns = table.settings().init().columns; table.columns().every(function(index) {      console.log(columns[index].name); })   

demo -> http://jsfiddle.net/6fstLmb6/

like image 151
davidkonrad Avatar answered Oct 06 '22 10:10

davidkonrad


below code worked for me

this.api().columns().every(function() {   console.log( this.header().textContent ) }) 

also you can add a specific html class for only specific column names like having that class

this.api().columns(".myColumnClass").every(function() {   console.log( this.header().textContent ) }) 
like image 34
Bhushan Kathar Avatar answered Oct 06 '22 10:10

Bhushan Kathar