Rutwick Gangurde
Rutwick Gangurde

Reputation: 4922

jQuery Datatables - Disable pagination and search if no results?

My AJAX call gets JSON data which can sometimes be empty. If I set the paginate option to true, the search and pagination components are shown even if I have 0 results. In which case I set the data to an empty object as [{}]. My settings are as follows:

processing: true,
serverSide: true,
autoWidth: false,
ordering: false,
searching:true,
lengthChange:false,
info: false

The JSON as follows:

draw: 1
length: 10
recordsFiltered: 10
recordsTotal: 1
start: 0
data: [..... list of items]

How to disable these two components if I have no data?

Update: I am not trying to change a setting after render, I am simply not able to understand why is Datatable showing pagination if the results are 0 and is there a way to avoid it. Currently I have hidden it using the xhr event to check the length of the data.

Upvotes: 2

Views: 2333

Answers (1)

Sinan Samet
Sinan Samet

Reputation: 6752

Based on this answer you have to use the drawCallback option to find out how many pages exist. You can then hide the pagination when the pages are equal to 1.

BitOfUniverse:

Use drawCallback option to handle DT draw event and show/hide pagination control based on available pages:

$('#table_id').dataTable({
  drawCallback: function(settings) {
    var pagination = $(this).closest('.dataTables_wrapper').find('.dataTables_paginate');
    pagination.toggle(this.api().page.info().pages > 1);
  }
})

Upvotes: 3

Related Questions