1

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?

12
  • 1
    You should really provide some code. Commented Jun 24, 2012 at 2:00
  • @holodoc What? Why? His question explains the issue perfectly well. Commented Jun 24, 2012 at 2:01
  • 2
    Because so many things are missing in his description like if he is trying to use inline JavaScript or perform the manipulation after the document (or at least DOM) has been loaded, is he using a framework or pure JavaScript, did he even try something before posting etc. etc. etc. Commented Jun 24, 2012 at 2:04
  • I agree with @holodoc. OP should show what they've tried. Can't tell what the actual issue is right now, Commented Jun 24, 2012 at 2:04
  • 2
    @david: Don't be obtuse. I've answered a lot more questions than you have on StackOverflow, and have seen plenty of times where OP excluded relevant code, only to discover when it was finally included that everything was correct but for a single important and very relevant detail. Instead of giving foolish examples as though they had comparable merit, you should encourage OP to provide detailed information. Commented Jun 24, 2012 at 2:20

3 Answers 3

7

This should be what you need.

var link = "http://www.google.com/";
var a = document.getElementById('yourlinkId');
a.href = link;
Sign up to request clarification or add additional context in comments.

1 Comment

Only if there's a relatively located document named www.google.com.
1

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

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

4 Comments

jQuery answers are irrelevant if OP isn't using it. And you're assuming there's a local document named www.google.com.
I am answering a question. If the OP doesn't like it he can choose to not mark it as the answer. Regarding the variable I created, that was to mimic whatever variable he might have grabbed from his form element.
The value of the variable can be misleading to someone inexperienced, as can using non-native and likely irrelevant syntax.
Then feel free to provide your own answer.
-3

If you're not using jQuery, try this:

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

1 Comment

document.write() is nothing but trouble.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.