PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, September 2, 2022

[FIXED] How to calculate the current page if the items per page changes to a smaller number?

 September 02, 2022     javascript, pagination     No comments   

Issue

I have the following issue - I have a pagination, that shows which part of the records you are looking at.

For example:

Total Items: 100
Possible Items per Page: 10, 25

If I set the items per page to 10 and go to page six this will get me the following:

51-60/100
  *   *
  |   |--------- Total records
  | 
  |-------- Displayed range of records

If change the page items per page to 25 it will be set to 51-75/100. But if I set it back to 10 it will display me 71-80.

It somehow feels like a weird behaviour, and I am sure, that the calculation that I came up with is faulty. I would think, that the right result should be 51-60 -> (set to 25 per Page) -> 51-75 -> (set to 10 per Page) -> 51-60

Here is my code:

itemsPerPageChanged(newItemsPerPage) {
    // On every change of the items per page the total amount of pages changes
    this.totalPages = Math.ceil(this.totalItems / newItemsPerPage);

    // Here I calculate the current page depending on the itemsPerPage size
    this.page = Math.ceil((this.itemsPerPage * this.page) / newItemsPerPage);

    // If the current page is bigger than total possible pages the ceil went to far and we take the last possible page as current page
    if (this.page > this.totalPages) this.page = this.totalPages;

    this.itemsPerPage = newItemsPerPage;
    this.getItems();
},

What is the right formula? I just can't get my head around it right now. :(


Solution

If you have first page's number 1, you should calculate page in the following way:

const pageFirstItemIndex = this.itemsPerPage * (this.page - 1) + 1;
this.page = Math.ceil(pageFirstItemIndex / newItemsPerPage);

and

displayedRangeOfRecords = `${itemsPerPage * (page - 1) + 1}-${itemsPerPage * page}`;


Answered By - all_you_need_is_laugh
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing