Search code examples
jquerydatatablesshow-hide

Show hidden columns in dataTables when check a checkbox


I'm trying to show columns hidden in the dataTable. I wrote my code as I understand from dataTables documentation, but it didn't work.

var $dtable = $('#example');
              var dtable  = $dtable.DataTable({
                  "scrollX": true,
                  "info":     false,
                  "dom": 'Bfrtip',
                  "columns": [
                        {"data": "name", className: 'profile', visible: true},
                        {"data": "position", className: 'sensitive', visible: false},
                        {"data": "office", className: 'profile', visible: true},
                        {"data": "age", className: 'sensitive', visible: false},
                        {"data": "startdate", className: 'profile', visible: true},
                        {"data": "salary", className: 'sensitive', visible: false}
                  ],
                  "buttons": [
                        'csv'
                  ]
              });

              $('.rect-check input').change(function(e){
                  console.log($(this).data('column'))

                  // Get the column API object
                  var column = $dtable.DataTable().column($(this).data('column'));

                  // Toggle the visibility
                  column.visible(true);
              })

the HTML

<div class="rect-check">
  <input data-column="sensitive" type="checkbox"> Show sensitive
</div>

<table width="100%" class="display" id="example" cellspacing="0">
....

check full example on codepen


Solution

  • Since you are referencing to a class you must handle it as such:

    <input data-column=".sensitive" type="checkbox"> Show sensitive
                        ^ or add a dot when you retrieve it. 
    

    Then it works. Use columns to get multiple columns and not just the first hit, and iterate over the result :

    $('.rect-check input').change(function(e){
      // Get the column API object
      var className = $(this).data('column');
      var columns = dtable.columns(className);
      // Toggle the visibility
      columns.each(function() {
        this.visible(true)
      })  
    })
    

    moved your codepen to a fiddle -> http://jsfiddle.net/s8005xg1/