I'm trying to implement a simple pagination project while I got stuck with a search bar issue.
Here's what I've accomplished so far:
- 10 entries are displayed per one page
- my script can calculate the total number of page links based on total number of entries(students)
- I can visit every single page and see its entries (say, page 1: students from 0 to 9... page 3: students from 30 to 39, etc)
- The search function
- I deliberately turned off a search by button. It's only available with 'keyup' event listener.
What I failed to implement so far:
When typing a search query: '/15', 2 pages are displayed with according entries. But then if I click on page 2 link, it displays more than 10entries per page(default parameter) and going back to page 1 the same error occurs. I suspect the page links get a wrong value from somewhere else. I tried to debug and it seems as if they're getting the value from $studentList(the whole list of students) but not from the search results that I pass there.
In all, I have 3 functions
function showPage(studentList, pageNum = 1){
const showPerPage = 10;
$(studentList).hide();
const calcStart = (pageNum) => pageNum === 1 ? 0 : (pageNum - 1) * showPerPage;
const start = calcStart(pageNum);
const end = pageNum * showPerPage;
$(studentList).slice(start,end).each(function(i, li){
$(li).fadeIn(50);
});
}
function appendPageLinks(studentList){
totalPageNum = Math.ceil(studentList.length / 10);
const pagination = 'pagination';
if($('.pagination').length === 0){
$('.page').append(`
<div class="${pagination}">
<ul></ul>
</div>
`);
}
$('.pagination ul').children().remove();
if (totalPageNum > 1){
for(let i=0; i<totalPageNum; i++){
const pageLink = `
<li>
<a href="#">${i + 1}</a>
</li>
`;
$('.pagination ul').append(pageLink);
}
}
$('.pagination ul li').children().first().addClass('active');
$('.pagination ul').on('click', 'a', function(e){
e.preventDefault();
const pgNum = parseInt($(e.target).text());
showPage(studentList, pgNum);
$(this).parent().siblings().children().removeClass('active');
$(this).addClass('active');
});
}
function searchStudent(element, filter){
$(element).each(function(){
if($(this).text().toUpperCase().includes(filter)){
$(this).show();
} else {
$(this).hide();
}
});
let num = $('.student-item:not([style*="display: none"])').length;
let searchRes = $('.student-item:not([style*="display: none"])');
num > 0 ? $('.notFound').hide() : $('.notFound').show();
return searchRes;
}
I think that these event listeners aren't getting the proper values:
$('.student-search input').on('keyup', function(){
const searchQuery = $(this).val();
const searchResults = searchStudent($('.student-list li'), searchQuery.toUpperCase());
showPage(searchResults);
appendPageLinks(searchResults);
});
As well as this one above
$('.pagination ul').on('click', 'a', function(e)
Here's a source code on codepen: https://codepen.io/hopper86/pen/WJmMMG?editors=1010
If someone could suggest how to fix to have the page links updated properly.