randombits
randombits

Reputation: 48490

Embed a javascript variable into my html anchor href

I have a piece of HTML which should look something like the following when rendered by the browser:

<b>This is a test</b><a href="foo.php?bar=yay">Test over!</a>

The problem I have is that foo.php is defined in a javascript var in the document. For argument sake, the name of the var is myPath. I'm trying to figure out how to get rid of the hard coded foo.php from the HTML above and have it read it from myPath instead.

I've tried different variations of escaping quotes and document.write() but haven't had much luck.

Is there a way to do something similar to:

<a href=" + myPath + "?bar=yay">

and have it render foo.php from myPath?

Upvotes: 1

Views: 1352

Answers (3)

Chris Wright
Chris Wright

Reputation: 773

If you give your link an ID, you can use that in your JavaScript to reference the element and modify its href.

<a href="#" id="js_link">

And then your JavaScript could look something like this:

window.onload = function() {
    var myPath = 'foo.php',
        link = document.getElementById('js_link');

    link.href = myPath;
}

Upvotes: 1

jack_tux
jack_tux

Reputation: 429

You should be able to use inline script to output your javascript variable. This might help How to output JavaScript with PHP

Upvotes: 0

Brino
Brino

Reputation: 2502

Just use getElementByID then set the href property.

Check out this working example.

(function () {
    var a = document.getElementById('mylink');
    var fooLink = 'foo.php';
    var link = fooLink + '?bar=yay';
    a.href = link;
})();

Upvotes: 0

Related Questions