JS - what could be causing this to not work properly? Could there be a bug that

Can anyone help me troubleshoot this code? It is supposed to add a search parameter page=value to the URL and load the page, but it's not working. I'm not sure if there's a typo in there.

$(function(){
     $('.page').on('click',function(){
         var page = $(this).text();
         var url = String(window.location);
         var newurl = "";
         if(url.indexOf("?") !== -1){
              if(url.indexOf('page') !== -1){
                 newurl = url.replace(/([&?]page=)[^&]*/, "$1" + String(page));
                 window.location = newurl;                            
              }else{
                 newurl = url +'&page='+String(page);
                 window.location = newurl;
              }
         }else{
             newurl = url +'?page='+String(page);
             window.location = newurl;

          }
        });
  });

html

<a href="" class="page">1</a>
<a href="" class="page">2</a>
<a href="" class="page">3</a>
<a href="" class="page">4</a>

Answer №1

The website's functionality is being disrupted by the default behavior of the browser when clicking on links. To resolve this issue, consider implementing preventDefault in your script.

$(document).ready(function(){
     $('.link').on('click',function(event){
     event.preventDefault();
         var linkText = $(this).text();
         var currentUrl = String(window.location);
         var newUrl = "";
         if(currentUrl.indexOf("?") !== -1){
              if(currentUrl.indexOf('link') !== -1){
                 newUrl = currentUrl.replace(/([&?]link=)[^&]*/, "$1" + String(linkText));
                 window.location = newUrl;                            
              }else{
                 newUrl = currentUrl +'&link='+String(linkText);
                 window.location = newUrl;
              }
         }else{
             newUrl = currentUrl +'?link='+String(linkText);
             window.location = newUrl;

          }
        });
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we troubleshoot webdriver cucumber when test steps are skipped due to passed arguments?

Greetings! I have a feature file outlined below in my cucumber webdriver test project: # language: en Feature: Simple Test, Int and Prod Origin vs non origin checks Simple cloud environment Checks @javascript @EnvCheck Scenario: Check Env TEST Orig ...

Unable to fetch data from MongoDB in Node.js when using objectid

After passing objectid of hospital 1 from Postman to this program, it only returns an empty array. However, there is data that matches that objectid. Can you assist me in resolving this issue? When attempting to debug the program in the console, it shows t ...

Failure to trigger Summernote's OnImageUpload function

After transitioning to the latest version of Summernote, which is Version 7, I encountered a problem with the image upload functionality. Despite specifying the line onImageUpload: function(files) {sendFile(files[0]);}, it seems that this code is not being ...

What could be the reason for the malfunction of my checkbox styling?

I have designed custom checkboxes and radio buttons with CSS styling as shown below: input[type="checkbox"]:checked + label:after, input[type="checkbox"][checked="checked"] + label:after, input[type="radio"][checked="checked"] + label:after, input[type="r ...

What is the best way to use res.sendFile() to serve a file from a separate directory in an Express.js web application?

I have a situation within the controllers folder: //controler.js exports.serve_sitemap = (req, res) => { res.sendFile("../../sitemap.xml"); // or // res.send(__dirname + "./sitemap.xml") // But both options are not working }; ...

Having trouble with the Django built-in logout redirect feature? Check out the MDN Tutorial Library for solutions

Can someone please assist me with getting the Django built-in logout page to function properly? The login is working without any issues. However, when I try to logout, it takes me back to the admin window instead of redirecting me to the login.html page. I ...

Choosing specific information in Typescript response

I am encountering an issue with my HTML where it displays undefined(undefined). I have checked the data in the debugger and I suspect that there may be an error in how I am using the select data. Here is a snippet of the code: <div *ngIf="publishIt ...

Utilizing AngularJS to calculate elapsed time and continuously update model and view accordingly

Situation Currently, I am interested in developing a web application that tracks a specific data set based on the time since the page was loaded. For example, "how many calories have you burned since opening this webpage?" I am still trying to grasp the ...

How can data be sent to the server in JavaScript/AJAX without including headers?

JavaScript - Is it possible to transfer data to the server backend without using headers? ...

The GLTFLoader does not support the replacement of its default materials

I am currently working on a scene that includes: AmbientLight color: light blue PointLight color: pink a gltf object loaded with textures Using the GLTFLoader, I successfully loaded a gltf object with texture map. The model is displayed correctly with ...

Guide on obtaining the dictionary of RequestContext imported from the django.template package

In my Django project, I am working with the following code snippet. ctxt = RequestContext(request, { 'power': power, 'attack': attack, 'defense': defense, }) My goal is to retrieve this dictionary from ctxt a ...

Refresh Ajax/Javascripts following the loading of new data with .html() function

My website has a page that utilizes an ajax function to load data into the page. The ajax function is as follows: $(document).ready(function(){ function loadData(page){ $.ajax ...

Add a new component to a Vue.js instance that is already in use

Just getting started with Vue.js I'm looking to register a local component following the instructions here: https://v2.vuejs.org/v2/guide/components.html#Local-Registration The catch is that I need to register the component to an existing Vue insta ...

Retrieve a targeted table from a webpage through Ajax refresh

On a webpage, I have a table that has two different views: simple and collapsible. I want to be able to toggle between these views using a button click without the need to refresh the entire page. Below is the code snippet I am currently using: $(&apo ...

I am experiencing issues with my JavaScript not functioning properly in conjunction with my HTML and CSS. I am uncertain about the root cause of the problem (The console is displaying an error message:

I am facing challenges in creating a content slider and encountering issues with its functionality. Specifically, when testing locally, I noticed that the current-slide fades out and back in upon clicking the arrows left or right, but the slide content is ...

What is the best way to incorporate currency formatting into a table using sumtr and datatables?

I have a table where I am utilizing sumtr for the table footer, and displaying all the information within datatables. My requirement is to show all the values as currency. However, I am unable to modify the values after sumtr because it won't be able ...

Achieving perfect alignment of an iframe on a webpage

Having an issue with aligning the iframe on my website. I have two buttons set up as onclick events that connect to internal pages displaying PHP data in tables within the iframe. Despite trying various CSS styles and positioning methods, I can't seem ...

Checking the Signature with Elrond in the Backend using PHP

My latest decentralized application allows users to log in using their Elrond wallet and generate a unique signature containing their wallet address and additional data. As part of the authorization process, the signature is included in the payload of req ...

site.js problem

Recently, I decided to create my very own CS:GO gambling website. After successfully setting it up on my localhost using VPS, I moved on to getting a domain and finalizing everything. However, when attempting to run site.js, an error message popped up: [e ...

Struggling to save a signature created with an HTML5 Canvas to the database

I've been on the hunt for a reliable signature capture script that can save signatures to MySQL, and I finally found one that fits the bill. However, there are two issues that need addressing: The canvas doesn't clear the signature when the c ...