Can't access .columns().names()

Can't access .columns().names()

vismarkvismark Posts: 79Questions: 5Answers: 0

Following the example from this docs page, i tried to replicate it in the following code:

var table = $('#myTable').DataTable();
console.log(table.columns().names())

But I'm getting:

TypeError: table.columns(...).names is not a function

What could be gone wrong?

Replies

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin

    As the docs page you linked to shows, that is due to be introduced in DataTables v2 (which is still very early in development - a long way to go!).

    That method is not yet available I'm afraid.

    Allan

  • vismarkvismark Posts: 79Questions: 5Answers: 0

    ok I'm sorry then...any other method to access column title and / or column names?

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @vismark ,

    You could try columns().header(), something like this:

    table.columns().header().each(function(v) { console.log($(v).text()) })
    

    Cheers,

    Colin

  • vismarkvismark Posts: 79Questions: 5Answers: 0

    Thanks colin, this is returning th's text as inserted in the dom. In my case sometimes column title and column name doesn't match, how can I retrieve them both?

    To be more clear, what I do this in the init is this:

    $('#example').dataTable( {
      "columnDefs": [
        { "title": "My column title", "name": "My column name", "targets": 0 }
      ]
    } );
    
  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin
    edited April 2018

    The columns.name option is only designed to be used as a selector (for the columns() selector method). It is not used for the export data and there is no public API to get that data there I'm afraid.

    Allan

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @vismark ,

    Another way to get them, is to look directly in the settings object. So name and title will be:

    table.settings()[0].aoColumns[columnIndex].sName
    table.settings()[0].aoColumns[columnIndex].sTitle
    

    Cheers,

    Colin

  • vismarkvismark Posts: 79Questions: 5Answers: 0

    ok colin, combining both of your ansewers I should have a solution. thanks a lot!

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin

    Yeah - ideally don't use information from the settings object. It is considered to be private. it can, may and does change between versions at times, so use with caution.

    If you do use it, wrap any use into a plug-in API method so if it does break in future, you can update it in just one place.

    Allan

This discussion has been closed.