1

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?

randombits
  • 47,058
  • 76
  • 251
  • 433
  • 1
    look for javascript or jquery for DOM manipulation. so after page is rendered, you can modify href of the hyperlink or insert the hyperlink in it's parent node. – gp. May 28 '15 at 01:35

3 Answers3

1

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;
}
Chris Wright
  • 754
  • 1
  • 8
  • 19
0

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;
})();
Brino
  • 2,442
  • 1
  • 21
  • 36
0

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

Community
  • 1
  • 1
jack_tux
  • 419
  • 3
  • 8