问题
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