开发者

Toggle Column visibility using class in dataTables

I know that to toggle the visibility in a column using the dataTables plugin I only have to do:

function fnShowHide( iCol ){
    /* Get the DataTables object again - this is not a recreation, just a get of the object */
    var oTable = $('#content-table-redesign').dataTable();

    var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
    oTable.fnSetColumnVis( iCol, bVis ? false : true );
}

but is it possible to get the column using an ID or Class or another mean?

The thing is I am also allowing the user to drag and drop the columns to开发者_如何转开发 will and if I go by index then they may be clicking to hide "id" (column 0) but they moved it somewhere else and now whatever is in the position 0 gets hidden instead of the "id" one.

Either that, or somehow trick the plugin to still link the column index regardless of where it's moved to.

EDIT

Here's the HTML the body is basically the same (each td has the same class as its th parent)

 <table id="content-table-redesign" class="display">
            <thead>
                <tr>
                    <th class="ID">ID</th>
                    <th class="Name">Name</th>
                    <th class="Domain">Domain</th>
                    <th class="email">email</th>
                </tr>
            </thead>
            <tbody>

I'm looking for the class, because the one that contains that class is the one that will be removed thead and tbody alike


I think the easiest answer is simply that dataTables doesn't support this natively and that you'll need to manually pull the index based on class yourself. Luckily, this is easy!

var iCol = $('#content-table-redesign tr').first().children('td.yourclass').index();
var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
oTable.fnSetColumnVis( iCol, bVis ? false : true );

Your selector may need to use th.yourclass depending on your table structure, of course. So it might read instead:

$('#content-table-redesign thead tr').children('th.yourclass').index();

UPDATE

Based on your HTML, here's your selector:

$('#content-table-redesign thead tr').children('th.ID').index();

You'll note the console logs "0": http://jsfiddle.net/YeAHB/


With the latest version of DataTables you can specify the class name and show/hide the columns.

var data_table = $('#data-table').DataTable();
data_table.columns('.location-col').visible(true);

Hope this helps.


I've never used this plugin, but depending on the html structure, you can use jQuery .index() to find what is the index of the child...

Take a look at this fiddle:

http://jsfiddle.net/UwQ35/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜