8

I need to show and hide the columns of the datatable after doing a javascript test, but it doesn't work good.

This is my test javascript:

if ( $('#commune_to_display').val()==""){
    $('#utable td:nth-child(2)').hide();
    $('#commune_to ').hide();
}

This test works just in the first page of the datatable, after pagination the column is still visible.

How can I fix it? thanks for help

2 Answers 2

15

You can show/hide columns as shown below. Just replace 3 and 4 with your actual column indexes.

var table = $('#utable').DataTable();
table.column(3).visible(true);    // To show
table.column(4).visible(false);   // To hide
Sign up to request clarification or add additional context in comments.

Comments

5

JavaScript code like this:

$(document).ready(function() {
    var table = $('#example').DataTable( {
        "scrollY": "200px",
        "paging": false
    } );

    $('a.toggle-vis').on( 'click', function (e) {
        e.preventDefault();

        // Get the column API object
        var column = table.column( $(this).attr('data-column') );

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

html code like this:

<table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
</tbody>
    </table>

You can view and run the full example here: https://datatables.net/examples/api/show_hide.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.