Table Pagination

This tutorial will explain how to add pagination to the table data. Here I am extending the tablesorter plugin. Using this extended version you do the following functionalities

  1. Can display multiple tables on a single page and add the pagination separately
  2. Can change the number of rows to display for each table separately
  3. Can move to the selected pages on a click
  4. Can also use the first, next, previous and last buttons

Please click here to view the live demo.

Functions that needed to add for achieve the above functions:

AddPageList() function

The addPageList() function calculates the total number of the pages from the total number of table rows and number of rows/size selected from the dropdown list. This function also append add the pagination buttons dynamically on the selection.

function addPageList(table) {
     var c = table.config, i;
     c.totalPages = Math.ceil(c.totalRows / c.size);
     c.container.find('ul').empty();
     for (i = 1; i <= c.totalPages; i++) {
          c.container.find('ul').append('<li>' + i + '</li>');
     }
}

setPage() function

The setPage() function takes the table and the selected page number [num] as the arguments. Then this function call the moveTopage() function which helps to navigate to the selected page.

function setPage(table, num) {
    var c = table.config;
    c.page = num;
    c.totalPages = Math.ceil(c.totalRows / c.size);
    moveToPage(table);
               
}

addClass() Function

The function adds ‘active ’ class to the selected ‘li’ and removes the ‘active’ classes from the remaining ‘li’s.

function addClass(table)
{
    var c = table.config;
    c.container.find(c.goTo).children().removeClass('active');
    c.container.find('li').eq(c.page).addClass('active');
}

click Event

For navigate to the selected page we need to add click event corresponding to the each ‘li’. The $(this).html() select the page number ( pageNum) from which we can identify the selected page number.

$(config.goTo,pager).on('click','li', function() {
     pageNum  = parseInt($(this).html())-1;
     setPage(table, pageNum);
     return false;
});

Click here to download the customized code.
If you have any further suggestion or queries please leave a comment below.

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

*