0

I have following java script code:

var product = getQueryVariable("product");

$('a.link').each(function()
{
    $(this).attr("href", $(this).attr("href") + "&product=" + getQueryVariable("product"));
});

function getQueryVariable(variable)
{
    var query = window.location.search.substring(1);        

    var variables = query.split("&");

    for (var iCount = 0; iCount < variables.length; iCount++)
    {
        var pair = variables[iCount].split("=");

        if (pair[0] == variable)
            return pair[1];
    }
}

If url is: http://www.xxxx.com/index.htm?product=abc, It sets a link to an anchor tag

<a class="link" href="http://www.aaaa.com/index.htm">Click here</a>

as

<a class="link" href="http://www.aaaa.com/index.htm?product=abc">Click here</a>

which is what I want, and it does it well.

But if anchor tag already has product variable in its href like

<a class="link" href="http://www.aaaa.com/index.htm?product=xyz">Click here</a>

then I get

<a class="link" href="http://www.aaaa.com/index.htm?product=xyz&product=abc">Click here</a>

while I was expecting that if product variable is present in href of anchor tag, it will replace existing product variable. And if there is no product variable in href tag, it will append it.

The code appends well, but does not replace existing product variable in href of anchor tag.

So, the question is how do I get 'product' param from all a tags that have class 'link'? so that I can replace it in my code if found. And can I fetch it in $('a.link').each(function() ?

How can I do it?

Computer User
  • 2,549
  • 2
  • 36
  • 62
  • 1
    Possible duplicate of [add or update query string parameter](http://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter) – LostMyGlasses Feb 03 '16 at 11:50
  • a good solution to this is ... get all your params from url and then all params from your `a` tag links and then remove the duplicates and then form a new query string. – Harry Bomrah Feb 03 '16 at 11:53
  • @LostMyGlasses thanks for quick reply. My page is at: http://products.softsolutionslimited.com/img2ocr/register1.htm?product=jpg2word I already have added https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js in it. what should be the new code? – Computer User Feb 03 '16 at 11:54
  • @HarryBomrah thanks for quick reply. My page is at: http://products.softsolutionslimited.com/img2ocr/register1.htm?product=jpg2word I already have added ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js in it. what should be the new code? – Computer User Feb 03 '16 at 11:55
  • @ComputerUser do u want to change all the links in this page? – Harry Bomrah Feb 03 '16 at 11:57
  • @HarryBomrah no, there is "Click here" hyperlink in the page http://products.softsolutionslimited.com/img2ocr/register1.htm?product=jpg2word . That 'click here' of anchor tag takes user to the payment page and must forward the same product from the url. Please see "Click here" hyperlink in page http://products.softsolutionslimited.com/img2ocr/register1.htm?product=jpg2word – Computer User Feb 03 '16 at 12:00
  • @HarryBomrah how do I get 'product' param from all a tags that have class 'link'? so that I can replace it in my code if found. And can I fetch it in $('a.link').each(function() ? – Computer User Feb 03 '16 at 12:22

5 Answers5

0

You can do something like this:

function changeLinkQueries(link,parameter,replacedVal) {

  // This function is anonymous, is executed immediately and 
  // the return value is assigned to QueryString!
  var query_string = {};
  var query = link.split('?')[1];
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
     var pair = vars[i].split("=");
     // If first entry with this name
     if (typeof query_string[pair[0]] === "undefined") {
       query_string[pair[0]] = decodeURIComponent(pair[1]);
       // If second entry with this name
     } else if (typeof query_string[pair[0]] === "string") {
       var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
       query_string[pair[0]] = arr;
       // If third or later entry with this name
     } else {
       query_string[pair[0]].push(decodeURIComponent(pair[1]));
     }
  } 

  var queries = query_string,
    linkArr = [];
  queries[parameter] = replacedVal;

  for(query in queries){
    linkArr.push(query + '=' + queries[query]);
  }

  return link.split('?')[0] + '?' + linkArr.join('&');

};

The function usage is : changeLinkQueries(link,parameter,replacedVal):

  • link : is the link that you want to modify
  • parameter: the parameter you want to change
  • replacedVal: the value that you want to replace with it

Example: changeLinkQueries('http://www.aaaa.com/index.htm?product=xyz','product','test') returns ==> http://www.aaaa.com/index.htm?product=test

Add this function to your code and update your code to :

var product = getQueryVariable("product");

$('a.link').each(function(){
    $(this).attr("href", changeLinkQueries($(this).attr("href"),'product',getQueryVariable('product')));
});

function getQueryVariable(variable)
{
    var query = window.location.search.substring(1);        

    var variables = query.split("&");

    for (var iCount = 0; iCount < variables.length; iCount++)
    {
        var pair = variables[iCount].split("=");

        if (pair[0] == variable)
            return pair[1];
    }
}
Marox Tn
  • 122
  • 9
  • first of all this will not work if the url has product anywhere. Plus OP wants to replace the value of product if found not keep as it is. your code will just return the same link without modifying product value – Harry Bomrah Feb 03 '16 at 12:04
  • Please check my answer and test it, I believe it's the best one and easiest to implement – Marox Tn Feb 03 '16 at 13:14
0

Try this,

Array.prototype.contains = function(x){
  return this.indexOf( x ) > -1 ? true : false;
}

var getUrlVars = function(url){
    var vars = [], hash;
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++){
        hash = hashes[i].split('=');
        vars.push(decodeURIComponent(hash[0]));
        vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
     }
     if(vars[0] == url){
        vars =[];
     }
     return vars;
}


var getUrl = function(url){
    var urlParams = getUrlVars(window.location.href),
        linkParams = getUrlVars(url),
        altered = false;

    for(i = 0; i < linkParams.length; i++){
        var t = linkParams[i];
        if(urlParams.contains(t)){
            linkParams[t] = urlParams[t];
            altered = true;
        }
    }
    return altered ? url.split("?")[0] + "?" + linkParams.map(function(y){return y + "=" + linkParams[y]}).join("&") : url;
}

$("a.link").each(function (i,link) {
    link.attr("href",getUrl(link.attr("href")));
})
Harry Bomrah
  • 1,626
  • 1
  • 11
  • 14
0

Try this

$('a.link').each(function()
{
    $(this).attr("href", $(this).attr("href").split("product=")[0] + "product=" + getQueryVariable("product"));
});

This works with links already containing product value
Nijeesh
  • 825
  • 7
  • 11
0

This code worked:

$('a.link').each(function()
{
    var anchor_url = $(this).attr("href");
    var product_val = '';

    if (-1 == anchor_url.indexOf('&product='))
    {
        if (-1 == anchor_url.indexOf('?product='))
            product_val = anchor_url.substr(anchor_url.indexOf('?product=')+'?product='.length);
    }
    else
        product_val = anchor_url.substr(anchor_url.indexOf('&product=')+'&product='.length);

    if (product_val.indexOf('&') != -1) product_val = product_val.substr(0, product_val.indexOf('&'))

    if (product_val == '') new_link = anchor_url+'&product='+getQueryVariable("product");
    else new_link = anchor_url.split(product_val).join(getQueryVariable("product"));

    $(this).attr("href",  new_link);
});
Computer User
  • 2,549
  • 2
  • 36
  • 62
-1

i hope this will help,

$(this).attr("href", getQueryVariable($(this).attr("href"), "product"));

function getQueryVariable(hrefLink, variable)
{
    if(hrefLink.contains("product")){
        return hrefLink;
    }else{
        //write your code here and return full url

    }
}
Tariq Husain
  • 509
  • 3
  • 20
  • first of all this will not work if the url has product anywhere. Plus OP wants to replace the value of product if found not keep as it is. your code will just return the same link without modifying `product` value – Harry Bomrah Feb 03 '16 at 12:03
  • this will also give you true `var x = "http://www.softsolutionslimited.com/products/purchase.test.php"; x.contains("product"); // true` This is the same link from your click here link, just removed the params. – Harry Bomrah Feb 03 '16 at 12:10