/    Sign up×
Community /Pin to ProfileBookmark

Dynamic Hyperlink

I have a page that is accessed via another page which will always include with it one of four possible values in the query string. I need to add to my page a link with the URL dependent on the value of the query string. I have the code to determine the proper URL. It is along the lines of:

if (location.search == “?a”)
{
myURL = “page_a.htm”

etc.

My question is how to code the link to pick up myURL as the href value. I tried the following without success:

<a href=”<script type=’text/javascript’>document.write(myURL)</script>”>Text to display to user</a>

It does work if I document.write the whole line, like this:

<script type=”text/javascript”>document.write(“<a href=”+myURL+”>Text to display to user</a>”)</script>

Just wondered if there was another way. I think it is the ASP part of my brain speaking.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@Mr_JJul 19.2005 — Please try this example


[code=php]<script type="text/javascript">
myURL = "page_a.htm"

document.getElementById("lnk1").href=myURL

</script>

<a id="lnk1" href="#null">Text to display to user</a>[/code]
Copy linkTweet thisAlerts:
@betheballauthorJul 19.2005 — Thanks for the direction. I did find for the above to work, I had to place the javascript after the link. Otherwise, it triggered an error of document.getElementById(...) is null or not an object. I am assuming that is because the javascript executes before the rest of the page loads and so at the time of execution, document.getElementById("lnk1") does not yet exist. Right?
Copy linkTweet thisAlerts:
@Mr_JJul 19.2005 — You are correct.

Normally a function would be run onload


[code=php]<HTML>
<HEAD>
<TITLE>Document Title</TITLE>

<script type="text/javascript">
<!--
myURL = "page_a.htm"

function testHref(){
document.getElementById("lnk1").href=myURL
}

//-->
</script>

</HEAD>
<BODY onload="testHref()">

<a id="lnk1" href="#null">Text to display to user</a>

</BODY>
</HTML>[/code]
×

Success!

Help @betheball spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.1,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...