Question

Here I am stuck with a scenario where I want to edit href of anchor tag before redirect. My scenario is if href attribute of anchor tag do not contain QueryString then append previous page query string to href means, suppose my current page url is xyz?x=2&y=4 Current href

href="local/services"

After Edit

href="local/services?x=2&y=4"

I tried.

HTML:

<a href="http://localhost/services" onclick="appendString(this)">test link </a> 

JavaScript

function appendString(obj) {
   var url = obj.getAttribute('href');
    if (url.indexOf('?') != -1)
      obj.setAttribute('href') = url + window.location.search;
    }

also tried

function appendString(obj) {
    var url = obj.getAttribute('href');
     if (url.indexOf('?') != -1)
         window.location.href =  url + window.location.search;
      }

but no success. Please suggest a solution. Thanks.

Was it helpful?

Solution 2

Jed Burke pointed to your mistake. So you should use something like this:

function appendString(obj) {
    var url = obj.getAttribute('href');
    if (url.indexOf('?') != -1) obj.setAttribute('href', url + window.location.search);
}

or even simpler:

function appendString(obj) {
    if (obj.href.indexOf('?') != -1) obj.href += window.location.search;
}

OTHER TIPS

The parameters for 'setAttribute' are incorrect.

element.setAttribute(name, value);

Courtesy MDN : Element.setAttribute

You can use JQuery for this:

$('.myLink').click(function() {
$(this).attr("href", this.href + "?param=1");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top