Abraham Abraham - 1 month ago 10
HTML Question

Get index of hidden cell in a table with Responsive extension

I have a jQuery DataTables built and a button with a "checking" class in one of its cells, I would like to get the index of the cell that contains that button once I click the button.

In order to reach this I have been using the following code:

$("#table tbody").on('click','.checking',function(){
var index = '';
index = $("#table").DataTable().cell($(this).parents('td')).index();
console.log(index);
});


This has been working fine when the cell hasn't been hidden by the Responsive extension of the DataTables, however when that field is hidden this function throws an
undefined
value.

See the button "Go" on the screenshot below.

Datatable Image

Answer

CAUSE

When Responsive extension hides a column, by default it places all content into a separate tr node with one single td node as a list with multiple li nodes.

When your cell becomes hidden, code cell($(this).parents('td')) stops working because of the different markup.

SOLUTION

  • DataTables 1.10.11+ and Responsive 2.0.2+ only

    $('#table tbody').on('click','.checking',function(){
        var index = $('#table').DataTable().cell($(this).closest('td, li')).index();
        console.log(index);
    });  
    

    See this jsFiddle for code and demonstration.

  • DataTables 1.10+ and Responsive 1.0.3+

    This method uses deprecated method responsive.index() which may be removed in future versions and its use is discouraged.

    $('#example tbody').on('click','.checking',function(){
        var $cellNode = $(this).closest('td, li');        
    
        var cell;
        if($cellNode.is('td')){
           cell = $('#example').DataTable().cell($cellNode);
        } else {
           var cellIdx = $('#example').DataTable().responsive.index($cellNode);
           cell = $('#example').DataTable().cell($cellNode);
        }
    
        var index = cell.index();
        console.log(index);
    });    
    

    See this jsFiddle for code and demonstration.

Comments