...

View Full Version : How can i set the value of href



havey
09-29-2003, 07:42 PM
How can i set the value of href in the last line below with the function determined value? So when texter function is called the <link> tag's href value is written to what the function derives it to be.


<script>
function texter(valu)
{
x = valu;
if (x = 1)
{
document.write ("set href in the line below to text1.txt");
}
if (x = 2)
{
document.write ("set href in the line below to text2.txt");
}
if (x = 3)
{
document.write ("set href in the line below to text3.txt");
}
}
</script>

<link rel="alternate" media="print" href="set this?">

</head>

fredmv
09-29-2003, 07:50 PM
You can use the setAttribute method to do this. Also, your code could be shortened to only this:



<script type="text/javascript">
function foo(bar)
{
document.getElementsByTagName("link")[0].setAttribute("href", "text"+bar+".txt");
}
</script>


Then, called like this:



foo("1");


Which would result in the first <link> element's href attribute having the value of text1.txt.

havey
09-29-2003, 08:16 PM
Thank You very much
:) :)

fredmv
09-29-2003, 08:24 PM
Possible reasons for the error:


You called the function before the <link> element existed.
There was no <link> element defined.


Here's a working example of my code:



<html>
<head>
<title>test</title>
<link href="" />
<script type="text/javascript">
function foo(bar)
{
document.getElementsByTagName("link")[0].setAttribute("href", "text"+bar+".txt");
}

function foobar()
{
alert("The current value of the first <link> element's href attribute is: " + document.getElementsByTagName('link')[0].getAttribute('href'));
}
</script>
</head>

<body style="font-family: courier;">
<a href="#" onclick="foo('1');foobar();">foo('1');</a> |
<a href="#" onclick="foo('2');foobar();">foo('2');</a> |
<a href="#" onclick="foo('3');foobar();">foo('3');</a>
</body>
</html>


Edited: Heh, I guess you figured it out. You're welcome. :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum