Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 307
zola Avatar asked Jul 21 '17 08:07

zola


2 Answers

I suggest to use a slightly different approach for calculating the parameter.

var pagination = (page, total, itemsOnPage) => {
        var numberOfPages = Math.ceil(total / itemsOnPage),
            start = (page - 1) * itemsOnPage + 1,
            end = Math.min(page * itemsOnPage, total);

        return `${start} to ${end} of ${total} on page ${page} of ${numberOfPages}`;
    };
   
console.log(pagination(1, 14, 5));
console.log(pagination(2, 14, 5));
console.log(pagination(3, 14, 5));
console.log(pagination(3, 15, 5));
like image 102
Nina Scholz Avatar answered Oct 19 '22 06:10

Nina Scholz


You could use Math.min.

var end = Math.min(start + numberOfItemsPerPage - 1, totalItemsCount);

e.g.

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

var numberOfPages = Math.floor((totalItemsCount + numberOfItemsPerPage - 1) / numberOfItemsPerPage);
var start = (page * numberOfItemsPerPage) - (numberOfItemsPerPage - 1);
var end = Math.min(start + numberOfItemsPerPage - 1, totalItemsCount);

console.log(`${start} to ${end} of ${totalItemsCount}`);
like image 31
H77 Avatar answered Oct 19 '22 05:10

H77