问题
I am doing project in laravel. I have implemented DataTables as,
blade.php
<table id="userprofaneword-table" class="table table-condensed table-hover">
<thead>
<tr>
<th>{{ trans('labels.backend.report.profaneword.table.id') }}</th>
<th>{{ trans('labels.backend.report.profaneword.table.user') }}</th>
</tr>
</thead>
<tbody>
@foreach($profaneData as $profaneUser)
<tr>
<td>{{$profaneUser->user->id ?? '---'}}</td>
<td>{{$profaneUser->user->first_name ?? '---'}}
</td>
</tr>
@endforeach
</tbody>
</table>
Scripts
{{ Html::script("https://cdn.datatables.net/v/bs/dt-1.10.15/datatables.min.js") }}
{{ Html::script("js/backend/plugin/datatables/dataTables-extend.js") }}
{{ Html::script("https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js") }}
{{ Html::script("https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js") }}
{{ Html::script("https://cdn.datatables.net/buttons/1.5.1/js/buttons.html5.min.js") }}
<script>
$(function () {
$('#userprofaneword-table').DataTable({
"dom": "Bfrtip",
"lengthChange": true,
"autoWidth": true,
"searching": true,
"order": [[ 0, "desc" ]],
"language": {
"searchPlaceholder": "Search",
},
"buttons": [
{
"extend": 'excelHtml5',
"text": 'Export User Profanity Report',
"className":"btn btn-sm btn-primary pull-right",
"exportOptions": {
"columns": ":not(:last-child)",
}
}
],
"select": true,
"searchDelay": 500
});
});
</script>
Every thing works fine. I can export data from table, I just want hide export button if there is no data coming from controller.
回答1:
I believe you want to react on filtering and so on. And you just want to make the button invisible, not break the DOM layout. You can use drawCallback
and set visibility
according to the presence of rows :
drawCallback: function() {
var hasRows = this.api().rows({ filter: 'applied' }).data().length > 0;
$('.buttons-excel')[0].style.visibility = hasRows ? 'visible' : 'hidden'
}
Here is a demo -> https://jsfiddle.net/okednaqg/
回答2:
var table = $('#userprofaneword-table').DataTable();
var buttons = table.buttons( ['.edit', '.delete'] );
if ( table.rows( { selected: true } ).indexes().length === 0 ) {
buttons.disable();
}
else {
buttons.enable();
}
回答3:
You can use JQuery to disable/enable the button based on the row count. Here's an example where the CSV export is disabled if the row count is zero. You could tie this to rowCallback option or a custom event.
var table = $('#example').DataTable();
if ( ! table.data().count() ) {
table.buttons( $('a.dt-button.csv') ).disable();
}
来源:https://stackoverflow.com/questions/52166257/how-to-hide-datatables-export-button-if-no-data