65

I am implementing datatbales and according to my requirement, most of the things have been resolved except the pagination issue. In my case for every time pagination navigation is displaying. I want to disable the pagination navigation if there is only one page at all.How to do that? My code is like:

JS

<script>
  function fnFilterColumn(i) {

    $('#example').dataTable().fnFilter(
      $("#col" + (i + 1) + "_filter").val(),
      i
    );
  }
  $(document).ready(function() {


    $('#example').dataTable({
      "bProcessing": true,
      "sAjaxSource": "datatable-interestdb.php",
      "bJQueryUI": true,
      "sPaginationType": "full_numbers",
      "sDom": 'T<"clear">lfrtip',
      "oTableTools": {
        "aButtons": [

          {
            "sExtends": "csv",
            "sButtonText": "Save to CSV"
          }
        ]
      },
      "oLanguage": {
        "sSearch": "Search all columns:"
      }


    });


    $("#example").dataTable().columnFilter({
      aoColumns: [
        null,
        null,
        null,
        null
      ]
    });


    $("#col1_filter").keyup(function() {
      fnFilterColumn(0);
    });

  });
</script>

HTML

<table cellpadding="3" cellspacing="0" border="0" class="display userTable" aria-describedby="example_info">

  <tbody>
    <tr id="filter_col1">
      <td>Interest:</td>
      <td>
        <input type="text" name="col1_filter" id="col1_filter">
      </td>
    </tr>
  </tbody>
</table>


<table width="100%" border="0" align="center" cellpadding="2" cellspacing="1" class="form_table display" id="example">

  <thead>
    <tr>
      <th class="sorting_asc" width="25%">Interest</th>
      <th width="25%">Name</th>
      <th width="25%">Email</th>
      <th width="25%">Contact No</th>
    </tr>
  </thead>
  <tbody>

    <tr>
      <td colspan="4" class="dataTables_empty">Loading data from server</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </tfoot>


</table>
Lukas
  • 1,699
  • 1
  • 16
  • 49
Bappa
  • 799
  • 1
  • 9
  • 17
  • Did you want to *disable* (https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Attribute/disabled) the pagination buttons, or *hide* them? All the answers below hide/show. – Jeromy French Mar 13 '15 at 13:33

19 Answers19

89

Building off of Nicola's answer, you can use the fnDrawCallback() callback and the oSettings object to hide the table pagination after it's been drawn. With oSettings, you don't need to know anything about the table settings (records per page, selectors specific to the table, etc.)

The following checks to see if the per-page display length is greater than the total records and hides the pagination if it is:

$('#your_table_selector').dataTable({
    "fnDrawCallback": function(oSettings) {
        if (oSettings._iDisplayLength > oSettings.fnRecordsDisplay()) {
            $(oSettings.nTableWrapper).find('.dataTables_paginate').hide();
        } else {
             $(oSettings.nTableWrapper).find('.dataTables_paginate').show();
        }
    }
});

Documentation

Raj
  • 22,346
  • 14
  • 99
  • 142
sina
  • 1,091
  • 1
  • 8
  • 6
  • 6
    Shouldn't it be oSettings._iDisplayLength >= oSettings.fnRecordsDisplay() ? – Dmitry Chornyi Apr 25 '13 at 01:31
  • 12
    If you use the filter to get 1 page, the controls disappear as expected. However once you clear the filter and end up with more than one 1 page, the controls do not reappear. This can be fixed by calling .show() on the JQuery elements inside the condition's _else_. – GuiSim Sep 18 '13 at 19:04
  • @DmitryChornyi: >= would show the navigation if 10 results were returned on a 10 result page size. We don't want it to show unless there are page+1, so > is correct. – dev_row Jan 27 '14 at 20:20
  • 1
    Please add `|| oSettings._iDisplayLength == -1` to your `if`-clause. So you can use the 'all' option in lengthmenu and there you also don't need the pagination. And like @OMG said, the `else` part... See also my improved version. – algorhythm Mar 12 '15 at 13:06
  • This code is outdated. See my [answer](http://stackoverflow.com/a/33377633/1988326) for how to do this in V1.10 – mark.monteiro Oct 27 '15 at 20:17
  • You have to add else { $(oSettings.nTableWrapper).find('.dataTables_paginate').show();} part. If the data reload by ajax, then parameters come 0 first. Then comes real data count. – ahmet Jun 18 '18 at 14:30
44

You must hide them dynamically I think, you can use fnDrawCallback()

$('#example').dataTable({
    "fnDrawCallback": function(oSettings) {
        if ($('#example tr').length < 11) {
            $('.dataTables_paginate').hide();
        }
    }
});​

EDIT - another way found here could be

"fnDrawCallback":function(){
      if ( $('#example_paginate span span.paginate_button').size()) {
      $('#example_paginate')[0].style.display = "block";
     } else {
     $('#example_paginate')[0].style.display = "none";
   }
}
Mathias Müller
  • 22,203
  • 13
  • 58
  • 75
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
  • thanks a lot. But I think one extra bracket is there "if( $('#example tr').length < 11 ) ) ". Anyway I resolve the issue. Thanks a lot once again. But one issue, as in the datatables, we can select the record limit as 10,25,50,100. Then if I select other than default(10)then how can we fix that? – Bappa Jun 15 '12 at 13:14
  • 1
    @Bappa You should get the pagination from oSettings and dynamically set the value – Nicola Peluchetti Jun 15 '12 at 13:24
  • 1
    please tell how to get from oSettings and dynamically set the value – Bappa Jun 15 '12 at 13:26
  • @Bappa maybe you can simply get them from the select that does the pagination $('select[name=example_length]').val(); – Nicola Peluchetti Jun 15 '12 at 13:32
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/12604/discussion-between-bappa-and-nicola-peluchetti) – Bappa Jun 15 '12 at 14:15
  • This approach is decent enough, but I would encourage parsing the pagination text instead of checking length. Then you can change your defaults at will (or in the future) and never have to worry about remembering to find "< 11" ever again. It will just look for "page 1 of 1" and recognize that there's only one page. Besides, if I remember correctly, there's an option for users to specify how many records they want to retrieve per page. So the hard-coded "< 11" isn't always going to work. – Greg Pettit Jun 15 '12 at 14:36
  • @GregPettit of course you could do that, but be wary of i18n problems, in any case i added another snippets that simply check if there is a pagination button. I found that on dataTables forum. – Nicola Peluchetti Jun 15 '12 at 14:59
  • Good point about internationalization; the snippet you found would do the job much better than my suggestion! – Greg Pettit Jun 15 '12 at 15:01
  • This code is outdated. See my [answer](http://stackoverflow.com/a/33377633/1988326) for how to do this in V1.10 – mark.monteiro Oct 27 '15 at 20:17
34

This is the correct approach when working in V1.10+ of JQuery Datatables. The process is generally the same as in previous versions but the event names and API methods are slightly different:

$(table_selector).dataTable({
    preDrawCallback: function (settings) {
        var api = new $.fn.dataTable.Api(settings);
        var pagination = $(this)
            .closest('.dataTables_wrapper')
            .find('.dataTables_paginate');
        pagination.toggle(api.page.info().pages > 1);
    }
});

Documentation

mark.monteiro
  • 2,609
  • 2
  • 33
  • 38
  • 2
    Not as easy to read, but same functionality in one line: preDrawCallback: function (settings) { $(this).closest('.dataTables_wrapper').find('.dataTables_paginate').toggle((new $.fn.dataTable.Api(settings)).page.info().pages > 1); } – Peter Jacoby Aug 13 '16 at 03:15
  • 1
    Great solution! Unlike the `fnDrawCallback` and `css("display", "none")` solution this worked for me also when changing the page size or filtering. Don't know why that is, but I guess it's due to the event not being fired. – Juergen Jan 04 '18 at 17:46
  • In order to hide the **lengthMenu** too I use this code at the end: `$(this).closest('.dataTables_wrapper').find('.dataTables_length').toggle(settings.aLengthMenu[0][0] != -1 && settings.aLengthMenu[0][0] < api.page.info().recordsTotal);` – Tadeu Sampaio Jun 01 '21 at 01:02
33

See my feature plugin conditionalPaging.

Usage:

$('#myTable').DataTable({
    conditionalPaging: true
});

or

$('#myTable').DataTable({
    conditionalPaging: {
        style: 'fade',
        speed: 500 // optional
    }
});
mjhasbach
  • 906
  • 9
  • 18
  • 2
    It took a minute to find the correct CDN for conditionalPaging. In DataTables jargon, It's not a regular Plugin, nor an Extension , but a "feature plugin". Perhaps this will save someone a minute. Here's a current link to feature plugins CDN links https://cdn.datatables.net/plug-ins/1.10.19/features/ – webb Feb 19 '19 at 10:59
7

Add this code to your datatables initialisation request.

JQUERY

Apply to single datatable:

"fnDrawCallback": function (oSettings) {
  var pgr = $(oSettings.nTableWrapper).find('.dataTables_paginate')
  if (oSettings._iDisplayLength > oSettings.fnRecordsDisplay()) {
    pgr.hide();
  } else {
    pgr.show()
  }
}

Apply to all datatables:

"fnDrawCallback": null 

Edit datatables.js to apply the code site wide.

DreamTeK
  • 32,537
  • 27
  • 112
  • 171
5

jQuery

  • I tried with the following options, it worked for me

      $("#your_tbl_selector").dataTable({
      "pageLength": 3,
      "autoWidth": false,
      "fixedHeader": {"header": false, "footer": false},
      "columnDefs": [{ "width": "100%", "targets": 0 }],
      "bPaginate": true,
      "bLengthChange": false,
      "bFilter": true,
      "bInfo": false,
      "bAutoWidth": false,
      "oLanguage": {
       "oPaginate": {
         "sNext": "",
         "sPrevious": ""
       }
     },
     "fnDrawCallback": function(oSettings) {                 
          if (oSettings._iDisplayLength >= oSettings.fnRecordsDisplay()) {
            $(oSettings.nTableWrapper).find('.dataTables_paginate').hide();
          }
      }
    

    });

DataTable Output View

enter image description here

Bùi Đức Khánh
  • 3,975
  • 6
  • 27
  • 43
Aravind
  • 51
  • 1
  • 1
5

I'm doing following to achieve this goal, as it is more dynamic solution that is not expressed above. as first it is getting total number of pages and then decide to show/hide pagination. Beauty of this code is only if user change page length then it will not effected.

jQuery('#example').DataTable({
    fnDrawCallback: function(oSettings) {
        var totalPages = this.api().page.info().pages;
        if(totalPages == 1){ 
            jQuery('.dataTables_paginate').hide(); 
        }
        else { 
            jQuery('.dataTables_paginate').show(); 
        }
    }
});
Faisal Janjua
  • 703
  • 1
  • 8
  • 15
3

I prefer @sina's solution. Good job.

But my one comes with some neccessary improvements. @sina forgot the else part to show the pagination again if neccesary. And I added the possibility to define the all option in the lengthMenu like following:

jQuery('#your_table_selector').dataTable({
    "lengthMenu": [[10, 25, 50, 100, 250, 500, -1], [10, 25, 50, 100, 250, 500, "All"]],

    "fnDrawCallback": function(oSettings) {
        if (oSettings._iDisplayLength == -1
            || oSettings._iDisplayLength > oSettings.fnRecordsDisplay())
        {
            jQuery(oSettings.nTableWrapper).find('.dataTables_paginate').hide();
        } else {
            jQuery(oSettings.nTableWrapper).find('.dataTables_paginate').show();
        }
    }
});
algorhythm
  • 8,530
  • 3
  • 35
  • 47
2

This callback function works generically with any datatable without having to hardcode the table ID:

$('.data-table').dataTable({
    fnDrawCallback: function(oSettings) {
       if(oSettings.aoData.length <= oSettings._iDisplayLength){
         $(oSettings.nTableWrapper).find('.dataTables_paginate').hide();
       }
    }
});
Agu Dondo
  • 12,638
  • 7
  • 57
  • 68
1

I know this is an old post but for those of us that will be using this, and have OCD just like me, a change is needed.

Change the if statement,

if (oSettings._iDisplayLength > oSettings.fnRecordsDisplay()) 

to

if (oSettings._iDisplayLength >= oSettings.fnRecordsDisplay()) 

With this little change you will see the pagination buttons for records lengths greater than 10, 25, 50, 100 instead of presenting the pagination buttons with only 10 records, technically 10, 25, etc records is still a one page view.

Cleb
  • 25,102
  • 20
  • 116
  • 151
Ray
  • 483
  • 4
  • 17
1

Just add the following to your stylesheet:

.dataTables_paginate .paginate_button.disabled {
    display: none;
}
Nikita
  • 11
  • 1
1

You can follow this way also.

"fnDrawCallback":function(){
      if(jQuery('table#table_id td').hasClass('dataTables_empty')){
            jQuery('div.dataTables_paginate.paging_full_numbers').hide();
      } else {
            jQuery('div.dataTables_paginate.paging_full_numbers').show();
      }
 }

This worked for me.

sreekanth kuriyala
  • 1,197
  • 11
  • 11
1

I tried to make sPaginationType as Dynamic in datatable for every entry but i can't find proper solution for that but what i did was

"fnDrawCallback": function(oSettings) {
    $('select[name="usertable_length"]').on('change', function(e) {
        var valueSelected  = this.value;
        if ( valueSelected < 10 ) {
            $('.dataTables_paginate').hide();
        } else {
            $('.dataTables_paginate').show();
        }
    });
},
Tunaki
  • 132,869
  • 46
  • 340
  • 423
1
$('#dataTable_ListeUser').DataTable( {

    //usual pager parameters//

    "drawCallback": function ( settings ) {

    /*show pager if only necessary
    console.log(this.fnSettings());*/
    if (Math.ceil((this.fnSettings().fnRecordsDisplay()) / this.fnSettings()._iDisplayLength) > 1) {
        $('#dataTable_ListeUser_paginate').css("display", "block");     
    } else {                
        $('#dataTable_ListeUser_paginate').css("display", "none");
    }

    }
   });
Matoeil
  • 6,851
  • 11
  • 54
  • 77
0

If your data is not dynamic, i.e., server generates HTML table which is then enhanced by DataTables you can render the paging option on the server (I am using razor).

$("#results").dataTable({
  paging: @(Model.ResultCount > Model.PageSize ? "true" : "false"),
  // more ...
});
Julian Lettner
  • 3,309
  • 7
  • 32
  • 49
0

Here is my solution, it works also if you have multiple tables on the same page. It prevents the colision for example (table A must have pagination, and B must not).

tableId in my code is never undefined. If you haven't defined an ID for your table, dataTable will do it for you by adding something like 'DataTables_Table_0'

    fnDrawCallback: function (oSettings) {
        if ($(this).DataTable().column(0).data().length <= oSettings._iDisplayLength) {
            var tableId = $(this).attr('id');
            $('#' + tableId + '_paginate').hide();
        }
    }
Yacine MEDDAH
  • 1,211
  • 13
  • 17
0

This Solved my issues:

.dataTables_paginate .disabled {
   display:none;
}   
dataTables_paginate .disabled + span {
   display:none;
}   

Hope it helps you all

0
    $("#datatable").DataTable({
        "fnDrawCallback": function (oSettings) {
            if ($(oSettings.nTBody).find("tr").length < $(oSettings.nTableWrapper).find("select[name=fileList_length]").val()) {
                $(oSettings.nTableWrapper).children(".dataTables_paginate").hide();
            }
        }
    });
0

this worked for me:

if ($('#dataTableId_paginate').find('li').length < 4) {
    $('#segment-list_paginate').html('');
}
Fahim
  • 407
  • 4
  • 11