feng01
feng01

Reputation: 5

How to toggle column visibility based on hidden input value?

in my table every column header (except the first one) has an hidden input field named 'group'. I want to implement buttons to toggle the visibility of specific columns based on in which group they are. I'm stuck at finding the right column-selector to get all columns where e.g. the input field value is "group1".

At the moment my buttons look like this and with simple selector like ':gt(0)' it works perfectly.

buttons: [
    {
        extend: 'columnToggle',
        text: 'Toggle Group1',
        columns: //get all columns with input value equals 'group1'
    }
]

I already tried a few things with jquery selectors, but i cant get it to work properly.

I have build a little test case with datatables live : Testcase

Thanks for the help

Upvotes: 0

Views: 370

Answers (2)

Gyrocode.com
Gyrocode.com

Reputation: 58880

Try this code:

var table = $('#example').DataTable( {
   dom: 'Bfrtip',
   buttons: [
     {
       extend: 'columnToggle',
       text: 'Toggle Group1',
       columns: $('#example thead th input[value="group1"]').closest('th')  
     }
   ]
});

See updated example for code and demonstration.

However it would be better to use class names for th elements instead and toggle columns by class name, see excellent answer by Zejji Zejji.

Upvotes: 0

Zejji Zejji
Zejji Zejji

Reputation: 495

Instead of using hidden inputs, have you tried applying a class to each column and then toggling as follows?:

$(document).ready( function () {
  var table = $('#example').DataTable( {
    columns: [
    { className: "group1" },
    { className: "group2" },
    { className: "group1" },
    { className: "group2" },
    { className: "group2" },
    { className: "group2" },
  ],
    dom: 'Bfrtip',
    buttons: [
      {
        extend: 'columnToggle',
        text: 'Toggle Group1',
        columns: '.group1'
      },
      {
        extend: 'columnToggle',
        text: 'Toggle Group2',
        columns: '.group2'
      }
    ]
  });
} );

A live example can be found here: http://live.datatables.net/howaxeju/1/edit

See further the following page regarding applying classes to columns: https://datatables.net/reference/option/columns.className

Upvotes: 1

Related Questions