how to show and hide columns of using datatable jquery

有些话、适合烂在心里 提交于 2020-01-14 14:17:54

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/45301902/how-to-show-and-hide-columns-of-using-datatable-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!