how to calculate the number of items per page and their index using javascript?

Viewed 8429

I am building a pagination system for a table and want to show a text like 1 to 5 of 14 entries i have the following code

var totalItemsCount = 14;
var numberOfItemsPerPage = 5;
var page = 1;

var numberOfPages = Math.floor((totalItemsCount + numberOfItemsPerPage - 1) / numberOfItemsPerPage);

var start = (page * numberOfItemsPerPage) - (numberOfItemsPerPage - 1);

var end = start + numberOfItemsPerPage - 1;

console.log(`${start} to ${end} of ${totalItemsCount}`);

now this works well when the number of items per page can equally divide the total number of items but when that is not the case end will be incorrect. in the following case if the variable page is 3 end will be of by 1. how can i fix this?

3 Answers
Related