jQuery: table pagination
by Muthuraman B
HTML
<div class="body">
<div class="main-content">
<div class="row">
<div class="col-xs-6">
<div class="panel" id="panel_1">
<input type="text" placeholder="Search patient..." />
<button class="search"><i class="fa fa-search"></i></button>
<table border="1" style="width:100%">
<thead>
<tr>
<th>name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jack</td>
<td>30</td>
</tr>
<tr>
<td>Chris</td>
<td>49</td>
</tr>
<tr>
<td>Mike</td>
<td>40</td>
</tr>
<tr>
<td>Tom</td>
<td>43</td>
</tr>
<tr>
<td>Torres</td>
<td>76</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-xs-6">
<div class="panel" id="panel_2">
<label>Activity Feeds</label>
</div>
</div>
</div>
</div>
</div>
CSS
html,
body {
background: #eee;
margin: 0;
padding: 0;
}
.body {
padding-top: 79px;
position: relative;
overflow: hidden;
}
.main-content {
border-top: 0;
padding-right: 10px;
padding: 15px 15px 0;
}
.logo {
margin: 0 auto;
line-height: 2;
}
.menu-bar {
min-height: 79px;
position: fixed;
top: 0;
z-index: 999;
left: 0;
right: 0;
display: flex;
display: -webkit-flex;
flex-wrap: wrap;
padding: 11px 0 8px;
background-color: white;
border-bottom: 1px solid #e6e5e5;
}
.panel {
background: #fff;
padding: 15px;
height: 200px;
border-radius: 0;
}
.controls a {
padding: 3px;
border: 1px solid gray;
margin: 2px;
color: black;
text-decoration: none;
cursor: pointer;
}
.active {
background: darkblue;
color: white !important;
}
a.prev {
display: none;
}
JavaScript
var show_per_page = 2;
var number_of_items = $('tbody').children().size();
var number_of_pages = Math.ceil(number_of_items / show_per_page);
var current_link = 0;
function go_to_page2(page_num) {
start_from = page_num * show_per_page;
end_on = start_from + show_per_page;
$('tbody').children().hide().slice(start_from, end_on).show();
$('.page[longdesc=' + page_num + ']').addClass('active').siblings('.active').removeClass('active');
}
function previous2() {
new_page = current_link - 1;
//if there is an item before the current active link run the function
if ($('.active').prev('.page').length == true) {
go_to_page2(new_page);
}
}
function next2() {
new_page = current_link + 1;
//if there is an item after the current active link run the function
if ($('.active').next('.page').length == true) {
go_to_page2(new_page);
}
$("a.prev").show();
}
$('table').after('<div class=controls></div>');
var navigation_html = '<a class="prev" onclick="previous2()">...</a>';
while (number_of_pages > current_link) {
navigation_html += '<a class="page" onclick="go_to_page2(' + current_link + ')" longdesc="' + current_link + '">' + (current_link + 1) + '</a>';
current_link++;
}
navigation_html += '<a class="next" onclick="next2()">...</a>';
$('.controls').html(navigation_html);
$('.controls .page:first').addClass('active');
$('tbody').children().hide();
$('tbody').children().slice(0, show_per_page).show();