Best way to select columns given Index, name or a negative number

Best way to select columns given Index, name or a negative number

jLinuxjLinux Posts: 981Questions: 73Answers: 75

I have a section of code that will hide columns specified in an array, and currently, you can specify the index or the name, but I notice in some DataTables API methods, you can select columns using a negative integer, such as -1 to select the very last column.

I was wondering, what would be the best way to go to accomplish that?

This is just a broke down snippet of the code used for selecting the columns.

// Aray of columns to hide
var colList = [
    1,      // Col Index # 1 
    'ssid', // Col Name 'ssid'
    -1      // Col at end of table
];

// Iterate through each column within the table
api.columns().every( function () {
    if ( $.inArray(this.index(), colList) === -1 // Check column index # 
        && $.inArray(api.column(this.index()).dataSrc(), colList) === -1 ) // Check column name (dataSrc)
    { 
        api.column( this.index() ).visible( false );
    }
} );

Thanks!

This question has an accepted answers - jump to answer

Answers

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75

    I just tested doing something like this..

    var target = '-1';
    if ( this.index() === api.column( target ).index() )
    

    And it works... so I think that will suffice.. Unless someone else knows of a better way

  • jLinuxjLinux Posts: 981Questions: 73Answers: 75
    edited November 2015

    Is it possible to get the index of a column if you have the name used in columns.name? Im looking at the selector-modifier and I don't see anything about that

  • allanallan Posts: 63,761Questions: 1Answers: 10,510 Site admin
    Answer ✓

    That I would suggest is the correct way to do it.

    To get the column based on name, the column-selector documentation has this information. Use: {string}:name.

    Allan

This discussion has been closed.