[javascript] How to use pagination on HTML tables?

I am trying to use this Pagination library in my HTML table page (specifically light theme) but somehow I am not able to understand how to plugin this library in such a way in my HTML page so that I can have pagination code working in my HTML table..

Right now, I have HTML table without any pagination code working so my below HTML code will show you a table with all the rows in one page which is not what I want...

I want to show 6 items in my table in one page by using above pagination javascript.. And as soon as I click on second pagination tab, it should show me next six items and keep on going until it is finished..

Below is my full HTML code in which I have tried using the same above pagination javascript but it doesn't work for me..

<html>
<head>

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="../jquery.simplePagination.js"></script>
<link href="../simplePagination.css" rel="stylesheet" type="text/css" />


    <style type="text/css">
table {
    width: 40em;
    margin: 2em auto;
    }

    thead {
    background: #000;
    color: #fff;
    }

    td {
    width: 10em;
    padding: 0.3em;
    }

    tbody {
    background: #ccc;
    }

    </style>

    <script>

function test(pageNumber)
{

  var page="#page-id-"+pageNumber;
  $('.select').hide()
  $(page).show()

}

</script>

</head>

<body bgcolor="#F8F8F8">
    <table class="paginated">
        <thead>
            <tr>
                <th>A</th>

                <th>B</th>

                <th>C</th>

                <th>D</th>
            </tr>
        </thead>

        <tbody>
            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>

            <tr>
                <td>1</td>

                <td>2</td>

                <td>3</td>

                <td>4</td>
            </tr>
        </tbody>
    </table>

<div id="choose">
</div>


    <script language="javascript">
    $(function() {
        $('#choose').pagination({
            items: 20,
            itemsOnPage: 2,
            cssStyle: 'light-theme',
            onPageClick: function(pageNumber){test(pageNumber)}
        });
    });
    </script>

    </body>
</html>

Any simple jsfiddle example basis on my above HTML code and also combined with above pagination javascript will help me understand better in how to imlement this js on the HTML tables..

Thanks for the help..

NOTE:-

I am only interested in simplePagination.js solution only which I am currently trying to implement

This question is related to javascript jquery html css pagination

The answer is


With Reference to Anusree answer above and with respect,I am tweeking the code little bit to make sure it works in most of the cases.

  1. Created a reusable function paginate('#myTableId') which can be called any number times for any table.
  2. Adding code inside ajaxComplete function to make sure paging is called once table using jquery is completely loaded. We use paging mostly for ajax based tables.
  3. Remove Pagination div and rebind on every pagination call
  4. Configuring Number of rows per page

Code:

$(document).ready(function () {
    $(document).ajaxComplete(function () {
        paginate('#myTableId',10);
        function paginate(tableName,RecordsPerPage) {
            $('#nav').remove();
            $(tableName).after('<div id="nav"></div>');
            var rowsShown = RecordsPerPage;
            var rowsTotal = $(tableName + ' tbody tr').length;
            var numPages = rowsTotal / rowsShown;
            for (i = 0; i < numPages; i++) {
                var pageNum = i + 1;
                $('#nav').append('<a href="#" rel="' + i + '">' + pageNum + '</a> ');
            }
            $(tableName + ' tbody tr').hide();
            $(tableName + ' tbody tr').slice(0, rowsShown).show();
            $('#nav a:first').addClass('active');
            $('#nav a').bind('click', function () {

                $('#nav a').removeClass('active');
                $(this).addClass('active');
                var currPage = $(this).attr('rel');
                var startItem = currPage * rowsShown;
                var endItem = startItem + rowsShown;
                $(tableName + ' tbody tr').css('opacity', '0.0').hide().slice(startItem, endItem).
                    css('display', 'table-row').animate({ opacity: 1 }, 300);
            });
        }
    });
});

As far as I can see it on the website of that paginations plugin, the plugin itself doesn't do the actual pagination. The only thing it does is display a row of numbers, and display the correct buttons depending on the page you're on.

However, to actually paginate, you have to write the appropriate Javascript yourself. This should be placed in stead of this Javascript:

function test(pageNumber)
{

  var page="#page-id-"+pageNumber;
  $('.select').hide()
  $(page).show()

}

Which is code I'm guessing you've copy-pasted from somewhere but at the moment doesn't really do anything. If you don't know Javascript, going with another library that actually does pagination of a table is something you probably want to do.


Use tr to <tr class="paginate">

//Pagination

<div id="page-nav"></div>

//Script

 <script>
        jQuery(function($) {
            // Grab whatever we need to paginate
            var pageParts = $(".paginate");
    
            // How many parts do we have?
            var numPages = 100;
            // How many parts do we want per page?
            var perPage = 10;
    
            // When the document loads we're on page 1
            // So to start with... hide everything else
            pageParts.slice(perPage).hide();
            // Apply simplePagination to our placeholder
            $("#page-nav").pagination({
                items: numPages,
                itemsOnPage: perPage,
                cssStyle: "light-theme",
                // We implement the actual pagination
                //   in this next function. It runs on
                //   the event that a user changes page
                onPageClick: function(pageNum) {
                    // Which page parts do we show?
                    var start = perPage * (pageNum - 1);
                    var end = start + perPage;
    
                    // First hide all page parts
                    // Then show those just for our page
                    pageParts.hide()
                        .slice(start, end).show();
                }
            });
        });
    </script>

Pure js. Can apply it to multiple tables at once. Aborts if only one page is required. I used anushree as my starting point.

Sorry to the asker, obviously this is not a simplePagignation.js solution. However, it's the top google result when you type "javascript table paging", and it's a reasonable solution to many who may be considering a library but unsure whether to go that route or not.

Use like this:

addPagerToTables('#someTable', 8);

Requires no css, though it may be wise to initially hide table tBody rows in css anyway to prevent the effect of rows showing then quicky being hidden (not happening with me right now, but it's something I've seen before).

The code:

function addPagerToTables(tables, rowsPerPage = 10) {

    tables = 
        typeof tables == "string"
      ? document.querySelectorAll(tables)
      : tables;

    for (let table of tables) 
        addPagerToTable(table, rowsPerPage);

}

function addPagerToTable(table, rowsPerPage = 10) {

    let tBodyRows = table.querySelectorAll('tBody tr');
    let numPages = Math.ceil(tBodyRows.length/rowsPerPage);

    let colCount = 
    [].slice.call(
        table.querySelector('tr').cells
    )
    .reduce((a,b) => a + parseInt(b.colSpan), 0);

    table
    .createTFoot()
    .insertRow()
    .innerHTML = `<td colspan=${colCount}><div class="nav"></div></td>`;

    if(numPages == 1)
        return;

    for(i = 0;i < numPages;i++) {

        let pageNum = i + 1;

        table.querySelector('.nav')
        .insertAdjacentHTML(
            'beforeend',
            `<a href="#" rel="${i}">${pageNum}</a> `        
        );

    }

    changeToPage(table, 1, rowsPerPage);

    for (let navA of table.querySelectorAll('.nav a'))
        navA.addEventListener(
            'click', 
            e => changeToPage(
                table, 
                parseInt(e.target.innerHTML), 
                rowsPerPage
            )
        );

}

function changeToPage(table, page, rowsPerPage) {

    let startItem = (page - 1) * rowsPerPage;
    let endItem = startItem + rowsPerPage;
    let navAs = table.querySelectorAll('.nav a');
    let tBodyRows = table.querySelectorAll('tBody tr');

    for (let nix = 0; nix < navAs.length; nix++) {

        if (nix == page - 1)
            navAs[nix].classList.add('active');
        else 
            navAs[nix].classList.remove('active');

        for (let trix = 0; trix < tBodyRows.length; trix++) 
            tBodyRows[trix].style.display = 
                (trix >= startItem && trix < endItem)
                ? 'table-row'
                : 'none';  

    }

}

you can use this function . Its taken from https://convertintowordpress.com/simple-jquery-table-pagination-code/

function pagination(){
    var req_num_row=10;
    var $tr=jQuery('tbody tr');
    var total_num_row=$tr.length;
    var num_pages=0;
    if(total_num_row % req_num_row ==0){
        num_pages=total_num_row / req_num_row;
    }
    if(total_num_row % req_num_row >=1){
        num_pages=total_num_row / req_num_row;
        num_pages++;
        num_pages=Math.floor(num_pages++);
    }
    for(var i=1; i<=num_pages; i++){
        jQuery('#pagination').append("<a href='#' class='btn'>"+i+"</a>");
    }
    $tr.each(function(i){
        jQuery(this).hide();
        if(i+1 <= req_num_row){
            $tr.eq(i).show();
        }

    });
    jQuery('#pagination a').click(function(e){
        e.preventDefault();
        $tr.hide();
        var page=jQuery(this).text();
        var temp=page-1;
        var start=temp*req_num_row;
        //alert(start);

        for(var i=0; i< req_num_row; i++){

            $tr.eq(start+i).show();

        }
    });
}

For me, best and simplest way, Bootply http://www.bootply.com/lxa0FF9yhw#

First include Bootstrap to your project

Then include javascript file in which you write this code:

    $.fn.pageMe = function(opts){
    var $this = this,
        defaults = {
            perPage: 7,
            showPrevNext: false,
            hidePageNumbers: false
        },
        settings = $.extend(defaults, opts);

    var listElement = $this;
    var perPage = settings.perPage; 
    var children = listElement.children();
    var pager = $('.pager');

    if (typeof settings.childSelector!="undefined") {
        children = listElement.find(settings.childSelector);
    }

    if (typeof settings.pagerSelector!="undefined") {
        pager = $(settings.pagerSelector);
    }

    var numItems = children.size();
    var numPages = Math.ceil(numItems/perPage);

    pager.data("curr",0);

    if (settings.showPrevNext){
        $('<li><a href="#" class="prev_link">«</a></li>').appendTo(pager);
    }

    var curr = 0;
    while(numPages > curr && (settings.hidePageNumbers==false)){
        $('<li><a href="#" class="page_link">'+(curr+1)+'</a></li>').appendTo(pager);
        curr++;
    }

    if (settings.showPrevNext){
        $('<li><a href="#" class="next_link">»</a></li>').appendTo(pager);
    }

    pager.find('.page_link:first').addClass('active');
    pager.find('.prev_link').hide();
    if (numPages<=1) {
        pager.find('.next_link').hide();
    }
    pager.children().eq(1).addClass("active");

    children.hide();
    children.slice(0, perPage).show();

    pager.find('li .page_link').click(function(){
        var clickedPage = $(this).html().valueOf()-1;
        goTo(clickedPage,perPage);
        return false;
    });
    pager.find('li .prev_link').click(function(){
        previous();
        return false;
    });
    pager.find('li .next_link').click(function(){
        next();
        return false;
    });

    function previous(){
        var goToPage = parseInt(pager.data("curr")) - 1;
        goTo(goToPage);
    }

    function next(){
        goToPage = parseInt(pager.data("curr")) + 1;
        goTo(goToPage);
    }

    function goTo(page){
        var startAt = page * perPage,
            endOn = startAt + perPage;

        children.css('display','none').slice(startAt, endOn).show();

        if (page>=1) {
            pager.find('.prev_link').show();
        }
        else {
            pager.find('.prev_link').hide();
        }

        if (page<(numPages-1)) {
            pager.find('.next_link').show();
        }
        else {
            pager.find('.next_link').hide();
        }

        pager.data("curr",page);
        pager.children().removeClass("active");
        pager.children().eq(page+1).addClass("active");

    }
};

You need to give an id to the tbody of your table and to add a 'div' after the table for the pagination

     <table class="table" id="myTable">
            <thead>
                <tr>
                    <th>...</th>
                </tr>
            </thead>
            <tbody id="myTableBody">
            </tbody>
       </table>
       <div class="col-md-12 text-center">
           <ul class="pagination pagination-lg pager" id="myPager"></ul>
       </div>

When your table's data is loaded, just call this

$('#myTableBody').pageMe({pagerSelector:'#myPager',showPrevNext:true,hidePageNumbers:false,perPage:4});

where the 'perPage' value is to set how many elements per page you want to have.


Many times we might want to perform Table pagination using jquery.Here i ll give you the answer and reference link

Jquery

  $(document).ready(function(){
        $('#data').after('<div id="nav"></div>');
        var rowsShown = 4;
        var rowsTotal = $('#data tbody tr').length;
        var numPages = rowsTotal/rowsShown;
        for(i = 0;i < numPages;i++) {
            var pageNum = i + 1;
            $('#nav').append('<a href="#" rel="'+i+'">'+pageNum+'</a> ');
        }
        $('#data tbody tr').hide();
        $('#data tbody tr').slice(0, rowsShown).show();
        $('#nav a:first').addClass('active');
        $('#nav a').bind('click', function(){

            $('#nav a').removeClass('active');
            $(this).addClass('active');
            var currPage = $(this).attr('rel');
            var startItem = currPage * rowsShown;
            var endItem = startItem + rowsShown;
            $('#data tbody tr').css('opacity','0.0').hide().slice(startItem, endItem).
                    css('display','table-row').animate({opacity:1}, 300);
        });
    });

JSfiddle: https://jsfiddle.net/u9d1ewsh/


There's a easy way to paginate a table using breedjs (jQuery plugin), see the example:

HTML

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Gender</th>
      <th>Age</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr b-scope="people" b-loop="person in people" b-paginate="5">
      <td>{{person.name}}</td>
      <td>{{person.gender}}</td>
      <td>{{person.age}}</td>
      <td>{{person.email}}</td>
    </tr>
  </tbody>
</table>
<ul></ul>

JS

var data={ people: [ {...}, {...}, ...] };

$(function() {
  breed.run({
    scope: 'people',
    input: data,
    runEnd: function(){ //This runEnd is just to mount the page buttons
        for(i=1 ; i<=breed.getPageCount('people') ; i++){
        $('ul').append(
            $('<li>',{
            html: i,
            onclick: "breed.paginate({scope: 'people', page: " + i + "});"
          })
        );
      }
    }
  });
});

Every time you want to change pages, just call:

breed.paginate({scope: 'people', page: pageNumber);

More info.

Working example.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to pagination

How to use paginator from material angular? how to implement Pagination in reactJs In Flask, What is request.args and how is it used? Custom pagination view in Laravel 5 Simple pagination in javascript UITableView load more when scrolling to bottom like Facebook application How to use pagination on HTML tables? how to remove pagination in datatable Laravel Pagination links not including other GET parameters API pagination best practices