Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to include a random number variable inside the src attribute of img tag

I have an array of image urls that I need to randomly choose from.

var imagesArray = [
       "http://img/img_0.jpg"
     , "http://img/img_1.jpg"
     , "http://img/img_2.jpg"
     , "http://img/img_3.jpg"
     , "http://img/img_4.jpg"
     , "http://img/img_5.jpg"

    ];
    var num = Math.floor(Math.random() * 6); // 0...6
    var num1 = Math.floor(Math.random() * 6); // 0...6
    var num2 = Math.floor(Math.random() * 6); // 0...6

But instead of the image numbers, I need to include a random number from 0 to 5 in the src of my image tag like this:

<img src="http://img/img_[num].jpg" name="canvas" />

but [num] doesn't work

HTML

<form name="imageForm" class="form1">
  <table>
  <tr>
    <td>
      <input onclick="displayImage();" type=button value="Display Random Image">
    </td>
  </tr>
  <tr>
    <td>
      <img src="http://img/img_[num].jpg" name="canvas" />
    </td>


    <td>
      <img src="" name="canvas1" />
    </td>


    <td>
      <img src="" name="canvas2" />
    </td>
  </tr>
  </table>
</form>
like image 560
jojo li Avatar asked Oct 21 '25 04:10

jojo li


1 Answers

Here is the fiddle.

 <img id="img1" src="" name="canvas" />

then script,

 var img1=document.getElementById("img1");
    img1.src="http://img/img_"+num+".jpg";
like image 67
Muhammet Can TONBUL Avatar answered Oct 23 '25 20:10

Muhammet Can TONBUL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!