jQuery dataTables plugin for pagination of HTML tables

25 / Mar / 2014 by pulkit 9 comments

In my project on Angular.js I came across a use case where I needed to paginate the HTML tables . DataTable jQuery plugin is a perfect choice in order to accomplish this task.

Let us take a simple example to illustrate the use of dataTable plugin:

[js]
<html>
<head>
<style>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
</style>

</head>
<body>
<table id="countTable">
<thead>
<tr><th>Count</th></tr>
</thead>
<tbody>
<tr><td>5</td></tr>
<tr><td>4</td></tr>
<tr><td>3</td></tr>
<tr><td>2</td></tr>
<tr><td>1</td></tr>
<tr><td>10</td></tr>
<tr><td>9</td></tr>
<tr><td>8</td></tr>
<tr><td>7</td></tr>
<tr><td>6</td></tr>
<tr><td>15</td></tr>
<tr><td>14</td></tr>
<tr><td>13</td></tr>
<tr><td>12</td></tr>
<tr><td>11</td></tr>

</tbody>
</table>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
$(function(){
$("#countTable").dataTable();

})
</script>
</body>
</html>
[/js]

If you are generating HTML Table with the help of some server-side script and you want to paginate that table then all you need to do is $(“#id_of_your_table”) .dataTable().With the help of

[js]<thead></thead> and <tbody></tbody>[/js]

tags we specify head and body of the table to dataTables plugin .Do not forget to include jQuery and dataTables files in the order as mentioned in the code above .After running the code to your surprise you will notice that the table is sorted in ascending order of the first column. If you don’t want to sort the table then you can do this:

[js]
$("#countTable").dataTable({"bSort": false});
[/js]

You will also see Show Entries filter , Search box , Information about currently displayed rows and previous /next pagination . If you want to hide or show one or many of them then you can do it by specifying true/false for each attribute value . e.g suppose you need to hide Search box and
Show Enteries filter then you can do this by following way:

[js]

$("#countTable").dataTable({
"bPaginate": true,
"bInfo": true,
"bFilter": false,
"bLengthChange": false
});
[/js]

bPaginate : Pagination
bInfo : To show the information about the rows currently displayed
bLenghtChange : Number of records to display for each pagination
bFilter : Search box

You can set the true/false values of the attributes according to your need.

You can also set the default value to show the number of records for each pagination in the following way.

[js]
$("#countTable").dataTable({"iDisplayLength": 5 });
[/js]

FOUND THIS USEFUL? SHARE IT

comments (9)

  1. Pingback: Using pipeline in datatables | TO THE NEW Blog

Leave a Reply

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