Harun Acar
Harun Acar

Reputation: 119

How to change column visibility by Column ID in javascript?

I want to make a column visible if its checkbox is selected. I have this function:

function SaveTableSettings() {
    var notChecked = [], checked = [];
    var table = $('#data-table');
    $(":checkbox").each(function() {
        if(this.checked){
            checked.push(this.id);

        } else {
            notChecked.push(this.id);
        }
});

And I want to use the elements of the "checked" array and change corresponding column visibility with this function :

if (dataTableId == "data-table"&&toShow.length<1) {
    alert("in if");
    table.column(1).visible(false);
    table.column(2).visible(false);
    table.column(3).visible(false);
    table.column(4).visible(false);
} else {
    for (i = 0; i < toShow.length; i++) {

    }
}

where "toShow" is the same array with to "checked" I passed it as parameter. I want to make the column which is in the array visible .But I do not know what to do in the for loop. Thanks for any help

Upvotes: 0

Views: 818

Answers (2)

Daniel
Daniel

Reputation: 37061

You can use the Buttons extension for that purpose, and to be more precise you should use the column visibility plug-in for Buttons.

Here is the basic usage example:

$(document).ready(function() {
    $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'colvis'
        ]
    } );
} );

You have to include the relevant JavaScript files, for example:

Alternatively, use Download builder and include DataTables with Buttons and Column visibility modules.

p.s In case that you use old datatables (1.9.x you should use the ColVis extension

Upvotes: 2

davidkonrad
davidkonrad

Reputation: 85558

It is hard to debug your code without the markup / HTML, but to me it somehow seems like you are trying to use a sledgehammer to crack a nut.

Instead of id's (?) simply use an attribute to bind the checkbox to a certain column :

<input type="checkbox" data-column="0" checked/>

And in your SaveTableSettings() or whatever :

$("[data-column]").each(function() {
    table.column($(this).data('column')).visible($(this).is(':checked'));
})

a small demo -> http://jsfiddle.net/c0o48jmv/1/


The above can easily be changed to target id's instead of column indexes. Simply add id's to your <th>'s

<th id="col0">columnHeader</th>

and refer to those id's instead of the indexes

<input type="checkbox" data-column="#col0" checked/>

http://jsfiddle.net/d9q06cg0/

Upvotes: 1

Related Questions