I created a jQuery code for pagination. I have a table with large number of records in my HTML. I created the following jQuery code to divide them into several pages with 10 records per page.
Pagination is working perfectly without the next button function. When put the Next button code into the jQuery, Next button is working but when I click on a page, it is showing the next to the next page instead the clicked page. So I guess next page function is effecting to the page click function however. What is the wrong part here??
HTML:
<!-- table -->
<table class="table" id="transactionsTable">
<thead>
<tr>
<th class="th-width-20">DB</th>
<th>Transaction ID</th>
<th>Order ID</th>
<th>Amount</th>
<th class="th-width-10">City</th>
<th class="th-width-30">Items</th>
</tr>
</thead>
<tbody>
@foreach($transactions as $key1 => $transaction)
<tr class="cl">
<td>{{ $transaction[0] }}</td>
<td>{{ $transaction[1] }}</td>
<td>{{ $transaction[2] }}</td>
<td>{{ $transaction[3] }}</td>
<td>{{ $transaction[4] }}</td>
</tr>
@endforeach
</tbody>
</table>
<!-- pagination -->
<nav aria-label="dis pagination">
<ul id="next-page" class="pagination">
<li id="pre-page">
<a class="page-link" href="#" tabindex="-1">Previous</a>
</li>
</ul>
</nav>
jQuery:
<script type="text/javascript">
var numberOfItems = $("#transactionsTable tbody tr").length;
var perPage = 10;
var totalPages = Math.round(numberOfItems / perPage);
for (var i = 1; i < totalPages; i++){
$(".pagination").append("<li class='page-item'><a class='page-link' href='#'>" + i + "</a></li>");
}
$(".pagination").append("<li id='next-page'><a class='page-link' href='#'>Next</a></li>");
$('#transactionsTable tbody tr').hide();
$('#transactionsTable tbody tr').slice(0, perPage).show();
$('.pagination li.page-item:eq(0)').addClass('active');
//Page click function
$(".pagination li.page-item").on("click", function() {
if ($(this).hasClass("active")) {
return false;
}
else {
var currentPage = $(this).index();
var startItem = currentPage * perPage;
var endItem = startItem + perPage;
$(".pagination li").removeClass("active");
$(this).addClass("active");
$('#transactionsTable tbody tr').css('opacity','0.0').hide().slice(startItem, endItem).
css('display','table-row').animate({opacity:1}, 300);
}
});
//Next button click function
$("#next-page").on("click", function() {
var currentPage = $(".pagination li.active").index();
if (currentPage === totalPages) {
return false;
}
else {
currentPage++;
$(".pagination li").removeClass("active");
$('#transactionsTable tbody tr').hide();
var startItem = currentPage * perPage;
var endItem = startItem + perPage;
$('#transactionsTable tbody tr').css('opacity','0.0').hide().slice(startItem, endItem).
css('display','table-row').animate({opacity:1}, 300);
$(".pagination li.page-item:eq(" + (currentPage - 1) + ")").addClass("active");
}
});
</script>
Example Code snippet with 20 records and 5 records per page