Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Javascript variable in HTML <a> link

My code goes something like this -

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 
    "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title></title>


    <script type='text/javascript'>

    var random_generator;
    document.write('Random Selection: ');
    var arr=['One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten'];
    var randomnumber=Math.floor(Math.random()*10);
    random_generator=arr[randomnumber];
    document.write(random_generator+ '<br>');


    </script>

<style type="text/css">

</style>
<a href='www.xyz.com/Index1/Index2/Variable/Index4'>Good Morning</a>
</head>
<body> 
</body>  
</html>

In place of Variable in the tag, I want to use random_generator Javascript variable. How do I do that? Thanks in Advance.

NOTE: random_generator doesn't replace the entire link. Only a part of the link (/Variable/). Depending on this value, the user is shown different pages.

like image 803
Cafecorridor Avatar asked Feb 18 '23 18:02

Cafecorridor


2 Answers

Or maybe you could just write the link as inline js.

​<script>
document.write('<a href="http://www.xyz.com/Index1/Index2/' + random_generator + '/Index4">hello</a>');
</script>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
like image 139
Scrimothy Avatar answered Feb 27 '23 11:02

Scrimothy


I am not sure if i understand your problem. But the following should work if you are trying to dynamically set the link to href (assuming you are not using jquery).

<a href='http://www.xyz.com/Index1/Index2/Variable/Index4' id="index">Good Morning</a>
<script>
    var newUrl = document.getElementById('index').href;
    newUrl = newUrl.replace("Variable", random_generator);
    document.getElementById('index').href = newUrl;
</script>
like image 39
Slowcoder Avatar answered Feb 27 '23 12:02

Slowcoder