studentcoder
studentcoder

Reputation: 148

How to pass a Javascript variable into a HTML file

I'm new to Javascript and HTML. I have a little problem that I've been trying to fix but don't know how.

I'm trying to pass a variable from a method in a Javascript file into a HTML file, and use its value as if it were HTML code. I know that the Javascript file is passed correctly into the HTML, the problem is just getting the variable from it.

Here is the relevant Javascript method:

function getCode()  {
    var myCode ="Hello World";
    document.getElementById("myCode").innerHTML = "<a>" + myCode + "</a>";
}

And here is the relevant HTML code:

<body>
    <a href="myCode" onclick="getCode()">
    <code id="myCode" class="prettyprint"> myCode </code>
</body>

I don't know if I am doing it correct. I simply need the variable myCode to be turned into just HTML code, in other words myCode in the HTML should be turned to "Hello World" at this point:

<code class="prettyprint"> myCode </code>

Upvotes: 2

Views: 216

Answers (3)

adeneo
adeneo

Reputation: 318182

Should work just fine, but setting a href value means the anchor redirects when clicking it.

<a id="myCode" href="#" onclick="getCode()">click</a>
<code id="myCode" class="prettyprint"> myCode </code>

<script>
    function getCode()  {
        var myCode ="Hello World";
        document.getElementById("myCode").innerHTML = "<a>" + myCode + "</a>"; 
    }
</script>

FIDDLE

Upvotes: 2

boky
boky

Reputation: 835

Here's a JSFiddle that works: http://jsfiddle.net/bGQy5/

<body>
    <a href="#" onclick="getCode()">Click me</a>

    <br/><br/>

    <code id="myCode" class="prettyprint"> Text
        <a href="#">Test</a>
    </code>


</body>

window.getCode = function () {
   var myCode = "Hello World";
   document.getElementById("myCode").innerHTML = "<a>" + myCode + "</a>";
 }

Please note a few issues though:

  • you are not closing your first tag, this is not good
  • you should be setting a "HREF" tag on your link to make it clickable.
  • you need to have the reference to a function (e.g. by attaching it to window or similar)
  • you'd be better off using a javascript library, like jquery

Upvotes: 1

rid
rid

Reputation: 63442

When clicking the link, the browser will change the address bar to myCode, because that's what the anchor's href attribute points to.

I'm guessing this is not what you wanted, so you can change the value of the href attribute to something like # to prevent this from happening.

<a href="#" onclick="getCode()">

Upvotes: 2

Related Questions