How do I add a javascript variable to HTML image src tag

html, image, javascript, jquery, random

Solution

var randomImage = 1 + Math.floor(Math.random() * 20);    
var imgName = randomImage+".png";
$("#randImg").attr("src",imgName);

Demo: http://jsfiddle.net/a9Ltw/

Problem

I know this answer is out here, but I have been unable to find it (or at least recognize it when I saw it!). I'm a relative noob to jquery, so bear with me please. Problem: I have 20 images, named 1.png through 20.png. I would like a different image to display randomly each time a user clicks a button. What's working: My javascript code to generate the random number looks like this: ``` var randomImage = 1 + Math.floor(Math.random() * 20); ``` What's not... What I'm trying to do is pass the result of that to my HTML document as the name of the image, so that is reads something like this: ``` <img id="randImg" class="img_answer" src="randomImage.png"> ``` I tried concatenating, but can't seem to figure this out. Do I need to create a function that affects the img ID or class? Can anyone point me to the cleanest way to do this?

Original source