BRAINBUZZ media
BRAINBUZZ media

Reputation: 504

How do I use a JavaScript variable in a href?

I have a JavaScript variable I grabbed from a form field and I am trying to use it for the href = value in a link. What is the proper way to output this JavaScript variable in HTML?

Upvotes: 1

Views: 14565

Answers (3)

Kyle
Kyle

Reputation: 3042

If you're not using jQuery, try this:

document.write('<a href="'+variable+'">Link to some site</a>');

Upvotes: -3

Josh Mein
Josh Mein

Reputation: 28625

This should be what you need.

var link = "http://www.google.com/";
var a = document.getElementById('yourlinkId');
a.href = link;

Upvotes: 7

Gregg
Gregg

Reputation: 35864

Update the href value via javascript. Using something like jQuery it is as simple as:

var link = "www.google.com";
$("a").attr("href", link);

Upvotes: 1

Related Questions