Sal B Sal B -4 years ago 63
Javascript Question

Pass URL Parameters from one page to another

Trying to do the following:

Store params from url, i.g. mydomain.com/page.html?cid=123456

If a user clicks on a button (they have a class of .btn-cta) it will take the params ?cid=123456 and add them to the new page those buttons link to /tour.html

I'm currently doing 1/2 of that with passing the params to an iframe on the page, now I need to get the above part working:

var loc = window.location.toString(),
params = loc.split('?')[1],
iframe = document.getElementById("signupIndex"),
btn = $('.btn-cta');

iframe.src = iframe.src + '?' + params;

Answer Source

Here's how I'd do it using jquery:

 $('.btn-cta').each(function(i, el){
    $(this).attr({
        href: $(this).attr("href") + window.location.search
    });
});

And in Vanilla ES2015

document.querySelectorAll('.btn-cta')
    .forEach((el) => el.attributes.href.value += window.location.search);

This takes all the elements that have class .btn-cta and appends the page query string to each of their href attributes.

So if the page url is `http://domain/page.html?cid=1234

<a href="/tour.html" class="btn-cta">Tour</a>

becomes

<a href="/tour.html?cid=1234" class="btn-cta">Tour</a>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download