Gedeon Evina
Gedeon Evina

Reputation: 23

How to insert a javascript variable inside an <a href> html tag?

I want to insert a javascript variable inside an html link such that each time the value of the variable is changed, it changes immediately in the html link.

I have tried already many possiblities but unsuccesfull.My code is as follows:

<head>
  <title>Hello World</title>
</head>
<body>

CATEGORIE NAME: <input id="first_name">
DEVICE NAME: <input id="last_name">
<button id="say">Send!</button>

<hr>
<div id="result"></div>

<script>
function say_hi() {
    var fname = document.getElementById('first_name').value;
    var lname = document.getElementById('last_name').value;

    var html = 'CODE: <b>' + fname  + lname;

    document.getElementById('result').innerHTML = html;
}

document.getElementById('say').addEventListener('click', say_hi);


</script>
    <a href="http://barcodes4.me/barcode/c39/ +$html.png">Click this link</a>

</body>
</html>

Please what should i so so that the link takes directly each time the value of the variable "html" and adds in as part of the link

Upvotes: 0

Views: 1689

Answers (1)

slebetman
slebetman

Reputation: 113876

The DOM API is fairly simple. It follows almost exactly the same convention as the HTML. For example, the href attribute of the a tag is the href property of the a object.

What you need to do is make your a tag easier to find:

<a id="this_link" href="">Click this link</a>

Now in your script you can simply do:

var link = document.getElementById('this_link');
link.href = "http://barcodes4.me/barcode/c39/" + html + ".png"

Upvotes: 1

Related Questions