bobbybouwmann
bobbybouwmann

Reputation: 1013

Pass a js variable to a href

I'm working on some links and I can't get it to work! I would know how it works with php but I suck in js :P

So I use fancybox for some simple forms. But I need to pass the current url of document to that page, so we know where the one who filled the form in comes from! Every url is build like

example.com/city

So I need that city, so I can pass it to the iFrame, otherwise I need to make a page for each city...

<a class="button fancybox.iframe" id="offerte" data-fancybox-type="iframe" href="offerte.php?page=city">Offerte aanvragen <span>»</span></a>

Something like this works, but I can't get in the href the right way!

document.write(document.URL);

How can I get the page link and pass it in the href??

Upvotes: 0

Views: 112

Answers (4)

kcak11
kcak11

Reputation: 842

Please try the following code:

Assumption url: example.com/city --> example.com/paris

var u=window.location.href;
var city=u.substring(u.lastIndexOf("/")+1);
document.getElementById("offerte").setAttribute("href","offerte.php?page="+city);

Upvotes: 0

antyrat
antyrat

Reputation: 27765

You need to use location.href property. If don't need domain and protocol there you can use location.pathname.

Read more about Location object at MDN.

You mentioned that you used jQuery in your tags, so w/ jQuery you can do this in that way:

$( '#offerte' ).attr( 'href', location.pathname );

and if you need to pass it as argument try this:

$( '#offerte' ).attr( 'href', 'offerte.php?page=' + location.pathname );

Upvotes: 1

Dharmesh Patel
Dharmesh Patel

Reputation: 1891

you can try,

document.getElementById("offerte").setAttribute("href",location.href);

Upvotes: 0

Eugene P.
Eugene P.

Reputation: 2625

use window.location more information here http://www.w3schools.com/jsref/obj_location.asp

Upvotes: 0

Related Questions