简体   繁体   中英

How to remove columns in JQuery Datatables?

I want to remove the columns which have total = 0.

So I've tried in different ways.

First, I assigned ID to all columns, for example; every <td> is of column will have their ID eg: First columns <td ID = 'col_1'> , second column all <td ID = 'col_2'> etc. And then in when footer callback I've tried to remove if this column total is ZERO then this $("col_"+i).remove() ; this code removed table headers only so I've tried again with $("col_"+i).empty() but again it's just empty. <th> only

Then I've tried to hide the columns by creating dynamic but I don't get any values.

    "footerCallback": function ( row, data, start, end, display ) 
    {
        var api = this.api(), data;  
        var intVal = function ( i ) { return typeof i === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof i === 'number' ?    i : 0;};

        var col_gonna_invis = '[';
        for(i=1;i<length_of_coloumns;i++)
            {
                total_salary = api.column( i ).data().reduce( function (a, b) {return intVal(a) + intVal(b);},0 );
                $('#total_cont_'+i).html(total_salary); 
                if(total_salary == 0)
                {
                    col_gonna_invis += '{"targets": [ '+i+' ], "visible": false, "searchable": false },';
                }
            }
        col_gonna_invis += ']';alert(col_gonna_invis);  
    },

    "aoColumnDefs": col_gonna_invis;

Please someone help me fix this issue or please someone tell me how to hide or remove columns which footer total is 0.

Thank you in advance.

I will suggest you use the visible() API method along with the sum() plugin :

Enhance the API with a column().sum() method :

jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
    return this.flatten().reduce( function ( a, b ) {
        if ( typeof a === 'string' ) {
            a = a.replace(/[^\d.-]/g, '') * 1;
        }
        if ( typeof b === 'string' ) {
            b = b.replace(/[^\d.-]/g, '') * 1;
        }

        return a + b;
    }, 0 );
} );

now, in initComplete() you can very easy hide columns which have a total or sum() of 0 :

var table = $('#example').dataTable({
   //... 
   initComplete : function() {
      var api = this.api(), 
          colCount = api.row(0).data().length;
      for (var i=0; i<colCount; i++) {
          if (api.column(i).data().sum() == 0) {
              api.column(i).visible(false);
          }
      }     
    }
});

demo -> http://jsfiddle.net/qer7e5os/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM