Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html image src call javaScript variable

this is my code: I want to ask

<script type="text/javascript">

var total = 4;

</script>

How can I do this?

<img src="img/apple_" + total + ".png" id="imageBox"/>

I've been try to use call function and document.onload but it's not work at all, can somebody save me?

like image 527
Neo Avatar asked Feb 02 '16 09:02

Neo


3 Answers

You need to add html in JavaScript like this:

<div id="foo"></div>
<script type="text/javascript">

var total = 4;
document.getElementById('foo').innerHTML = '<img src="img/apple_' + total + '.png" id="imageBox"/>';
</script>
like image 83
jcubic Avatar answered Oct 24 '22 09:10

jcubic


I am supposing you just want to update the image src with javascript.

document.getElementById('imageBox').src = "img/apple_" + total + ".png";
like image 24
kp singh Avatar answered Oct 24 '22 09:10

kp singh


window.onload = function() {
  var total = 4;
  document.getElementById('imageBox').src = 'img/apple_' + total + '.png"';

};
<img src="" id="imageBox"/>
like image 1
Sunil Kumar Avatar answered Oct 24 '22 08:10

Sunil Kumar