Phil Barnes
Phil Barnes

Reputation: 133

How to pass a Javascript var into a href tag?

I have used a function to capture the Query String value of "name" - i.e. imagine a party invite site;

https://cometomyparty.com?name=phil

The function used is;

<script type="text/javascript">
  function getQuerystring(){
    var q=document.location.toString();
    q=q.split("?");
    q=q[1].split("&");
    var str=""
    for(i=0;i<q.length;i++){
      tmp=q[i].split("=")
      str+=" "+tmp[1]+"<br />"
    }
    document.getElementById("name").innerHTML=str
  }
  onload=function(){
    getQuerystring()
  }
</script>

Then I can call the value of 'name' using id="name" where I want to use this on my page, i.e. in the heading, I could say, Phil, looking forward to having you at the party...

How can I dynamically append my 'name' value (var str) within a html link placement i.e.

<a href="http://example.com?name=str">Link Text</a>

Which would return, in the example above;

http://example.com?name=phil

Upvotes: 0

Views: 2675

Answers (2)

Tom_B
Tom_B

Reputation: 327

Try this:

<a href="#" onclick='goToPage(event)'>Link Text</a>

<script>

function goToPage(event) {
    event.preventDefault();
    window.location='http://example.com?name='+str;
}

</script>

Ideally you would want to use jquery where you could use:

$('#link').click(function(event) {
    event.preventDefault();
    var link = $(this).attr('src');
    window.location=link+str
});

You would of course want to remove "str" from the href

Upvotes: 1

Pineda
Pineda

Reputation: 7593

You can access the href attribute of the <a> tag directly or by using .setAttribute:

// Using .href:
document.getElementById("name").href=str;

// Using . setAttribute:
document.getElementById("name").setAttribute ("href", str);

Be aware that you should have that <br/> tag in the src of the link.

Upvotes: 2

Related Questions