2

I have a URL https://example.com/fullimg.php?eid=1&pgno=&pdate=2022年12月24日,

I want to create a next and previous button. If the user clicks on the next button he will redirect to pgno=1 means the next page. If he clicks on the next button again he will be redirected to pgno=2 and so on if he clicks next again he will be redirected to pgno=3 here the pdate is dynamic and changes every day.

I have tried this

 let url = window.location.href;
 if (url.includes("pgno=")) {
 url = url.replace("pgno=", "pgno=2");
 } else if (url.includes("pgno=2")) {
 url = url.replace("pgno=", "pgno=3");
 }
 console.log(url);
 window.location.replace(url);

Also I have tried this

 let url = window.location.href;
 if (url.includes("pgno=")) {
 url = url.replace("pgno=", "pgno=2");
 } 
 if (url.includes("pgno=2")) {
 url = url.replace("pgno=", "pgno=3");
 }
 console.log(url);
 window.location.replace(url);

For both it's only executing first condition not the 2nd one. After clicking on the next button it's going to pgno=2 but after that when I am clicking next it's still reloading and redirecting to pgno=2

How can I solve it?

I have solved it, thanks to @Unmitigated

this is the function,

 function Next2() {
 let params = new URLSearchParams(location.search);
 // get the value of pgno
 let pgno = +params.get('pgno');
 // check if pgno is less than or equal to 12
 if (pgno <= 11) {
 // go to next page
 params.set('pgno', pgno + 1);
 location.search = params;
 }
 }

And here is the previous function

 function Prev1() {
 let params = new URLSearchParams(location.search);
 // get the value of pgno
 let pgno = +params.get('pgno');
 // check if pgno is greater than 1
 if (pgno > 1) {
 // go to previous page
 params.set('pgno', pgno - 1);
 location.search = params;
 }
 }
asked Dec 24, 2022 at 19:36
1
  • 1
    Nice reading here Commented Dec 24, 2022 at 19:43

1 Answer 1

3

Use URLSearchParams to facilitate handling query strings.

let params = new URLSearchParams(location.search);
// go to next page
params.set('pgno', +params.get('pgno') + 1);
location.search = params;
answered Dec 24, 2022 at 19:46
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, working. But how can I stop it when it reaches 12? And will it work for previous button if I use params.set('pgno', +params.get('pgno') -1); and stop when pgno is 1?
@MohammadFathiRahman You would need to manually check for the page number being equal to 1 or 12.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.