Pipo
Pipo

Reputation: 5599

How to hide or show column of table created using datatables in javascript?

Do you know how to hide or show column when datatable's source is javascript?

Methods for showing or hiding columns

 table = $('#example').DataTable();
var col = table.column("0").visible(false);

work when data source is directly into html

<table id="example" class="row-border hover">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
...          

But it does not work and launch an error when DataTable has a javascript source

 var table = $('#example').dataTable({
                   "data": source,
                    "columns": columns,
                    "columnDefs": defs
    });


 var col = table.column("0").visible(false);//ERROR!

Do you know how to hide a column of Datatables with a javascript source please?

Upvotes: 1

Views: 2273

Answers (2)

Pipo
Pipo

Reputation: 5599

I finally found another answere : it doesn't depends of html or json source but there is a difference between DataTable() which is the new version and dataTable() the old version

column(n).visible(bool) 

works for DataTable()

fnRowCallback 

works for dataTable()

Upvotes: 1

Lumi Lu
Lumi Lu

Reputation: 3305

Try something like this,

var table = $('#example').dataTable({
  "data": source,
  "columns": columns,
  "columnDefs": [
  {
    "targets": [ 0 ],
    "visible": false,
  },
  "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull )     
  {
    $('td:eq(0)', nRow).hide();
  }
});

Updated. Try to add fnRowCallback. thanks!

Upvotes: 1

Related Questions