Alan Khabitsov Alan Khabitsov - 6 months ago 9
HTML Question

How to insert variable into <img> src parameter?

I am trying to generate QR code on my webpage with a data (id) I get from web service. I can not figure out how to insert a javascript variable as a part of src parameter.

As you can see I can change the src using myFunction (AFTER button clicked). But I do not know how to insert id variable to the initial page load (to replace ID1_GOES_HERE at the end of img line).
Please help!

Here is a code:

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>TEST</title>
</head>
<body>

<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";

function myFunction(){
var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
document.getElementById('qr_img').src="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl="+id2;
}
</script>

<img id="qr_img" src="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl=ID1_GOES_HERE"/>
<button onclick="myFunction()">test</button>

</body>
</html>

Answer

Don't use a button click handler, just call the function from your script:

<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title>TEST</title>        
</head>
<body>

<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";

function myFunction(){
    var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
    document.getElementById('qr_img').src = "http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl="+id2;
}

myFunction();
</script>

<img id="qr_img" src="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl=ID1_GOES_HERE"/>
<button>test</button>

</body>
</html>

The click handler is used to capture the button click event, and do something at that time. That's not what you want, so remove the button click handler.

At the end of the <script> element, simply call myFunction() to do what it's intended for.

If you wanted to run the script after the entire document and all of its dependencies were loaded, you could do this:

<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";

function myFunction(){
    var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
    document.getElementById('qr_img').src = "http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl="+id2;
}

document.onload = myFunction();
</script>

For this simple case, you probably don't actually need a function at all, and the body of myFunction can simply be placed inline, like so:

<script>
var id1 = "41c0236f-ed21-4182-be3d-26513078f704";
var id2 = "41c0236f-ed21-4182-be3d-26513078f704";
document.getElementById('qr_img').src = "http://chart.apis.google.com/chart?cht=qr&chs=300x300&chld=H|0&chl="+id2;
</script>

The function would be useful if you had more logic involved, and needed to organize (or modularize) it.

Comments