This post is 6th part of a series called Getting Started with Datatable 1.10 .

  1. DataTable demo (Server side) in Php,Mysql and Ajax
  2. DataTable (Server side) Custom Column Search
  3. Datatable Scroller (Server Side)
  4. DataTable Responsive (Server side)
  5. Datatable Custom Loader
  6. Datatable Colvis (Column Visibility Customization)
  7. DataTable Table tools
  8. DataTable Custom Search By Tags Input (Server side)
  9. DataTable Search By Datepicker (Server side)
  10. Datatable Bulk Delete (Server Side)
  11. Datatable Page Resize (Server Side)

Column visibility always an important part of any gridview. That’s why some grid view provide it by default. You can use column visibility or datatable colvis to your datatable adding colvis extension . I have prepared a demo and customized some portion to make it more useful.

Add two assets more along with other assets

1
2
<link rel="stylesheet" type="text/css" href="css/dataTables.colVis.css">
<script type="text/javascript" language="javascript" src="js/dataTables.colVis.js"></script>

Enable datatable colvis simply adding a dom option at the time of initialization.

1
2
3
4
5
6
7
8
$(document).ready(function() {
    var dataTable =  $('#employee-grid').DataTable( {
        processing: true,
        serverSide: true,
        ajax: "employee-grid-data.php", // json datasource
        dom: 'C<"clear">lfrtip'    // enable colvis
    } );
});

Alternatively, we can enable using `new` initialisation

1
2
3
4
5
6
7
8
9
$(document).ready(function() {
    var dataTable =  $('#employee-grid').DataTable( {
        processing: true,
        serverSide: true,
        ajax: &quot;employee-grid-data.php&quot;, // json datasource
    } );
     var colvis = new $.fn.dataTable.ColVis( dataTable );
       $( colvis.button() ).insertAfter('div.info');
});

Datatable Demo6 Datatable Columnvis (Column Visibility) | CoderExample 2015-02-11 16-20-02

Let’s customize it.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
$(document).ready(function() {
    var dataTable =  $('#employee-grid').DataTable( {
        processing: true,
        serverSide: true,
        ajax: "employee-grid-data.php", // json datasource
    } );
    var colvis = new $.fn.dataTable.ColVis( dataTable, {
        buttonText: '<img src=&quot;images/down.gif" >',
        activate: 'mouseover',
        exclude: [ 0 ]
    } );
    $( colvis.button() ).prependTo('th:nth-child(1)');
 
});
  • Replaced “show / hide columns” text by an image using “buttonText” option.
  • Changed “click” event to “mouseover” by “activate” option.
  • Excluding first column (ie, Employee name) or index 0 from the list using “exclude” api.
  • Last, aligned button position to first column’s header .

Download full code from below link, feel free to comment if you have any query./supquot;javascript