table pagination javascript

Table Pagination with Javascript

Pagination is very important when it comes to displaying huge data in a table. It helps to make the table easy to read and navigate. In this blog post, we will discuss how to implement table pagination with Javascript.

Step 1: HTML Table

We need an HTML table to display data. We will create a sample table with 10 rows and 3 columns.


<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Country</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John</td>
      <td>25</td>
      <td>USA</td>
    </tr>
    <tr>
      <td>Mike</td>
      <td>30</td>
      <td>Canada</td>
    </tr>
    ...
  </tbody>
</table>

Step 2: Javascript Code

We will use Javascript to implement table pagination. We will create a function called paginate() that will handle the pagination logic.


function paginate(pageNum){
  var rowsPerPage = 5; // number of rows to show per page
  var myTable = document.getElementById("myTable");
  var rows = myTable.getElementsByTagName("tr");
  var totalPages = Math.ceil((rows.length-1) / rowsPerPage); // -1 to exclude the table header row
  var startIndex = (pageNum - 1) * rowsPerPage + 1;
  var endIndex = startIndex + rowsPerPage - 1;
  
  if(endIndex > rows.length) endIndex = rows.length-1; // adjust endIndex if it exceeds the number of rows
  
  // loop through all the rows and hide/show them based on the page number
  for(var i=1; i= startIndex && i <= endIndex){
      rows[i].style.display = "table-row";
    } else {
      rows[i].style.display = "none";
    }
  }
  
  // display the pagination links
  var paginationLinks = "";
  for(var i=1; i<=totalPages; i++){
    if(i == pageNum){
      paginationLinks += "<span>" + i + "</span>";
    } else {
      paginationLinks += "<a href='javascript:paginate(" + i + ")'>" + i + "</a>";
    }
  }
  document.getElementById("pagination").innerHTML = paginationLinks;
}

We need to display the pagination links somewhere in the HTML. We will create a div with an id of "pagination" where we will display the links.


<div id="pagination"></div>

Step 4: Testing

Now we can test our pagination by calling the paginate() function with a page number as an argument. For example, to display the first page, we will call paginate(1).


<button onclick="paginate(1)">First Page</button>
<button onclick="paginate(2)">Second Page</button>
...

That's it! Now we have implemented table pagination with Javascript.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe