Kilisi Kilisi - 1 month ago 8
Javascript Question

Return a variable to use as image src

I have a variable image that needs to display based on another form field so if the first form field says XYZ123 then the picture I need displayed will be in the server filesystem already and named XYZ123.jpg

I can't work out the syntax to put it in

<td colspan=3 align="center"><img src="pictures/thumbnails/logo-20170820013631.jpg" alt="Logo" border=1 height=150 width=150></img><br>Click to enlarge.</td>


This works fine if I use a static image name, but I need dynamic

I have a function that is called whenever the first field is changed

<div><b>EDIT CUSTOMER DETAILS</b><br><input type="text" name="key" onchange="changedReference(this.name);" placeholder="enter customer ID"></div> //calls function

function changedReference(n)
{
var ref = EL(n).value;
var img = EL(n).value;
if (ref == null || ref == "") return;

var x = getXmlHttpRequest();
if (x == null) {
alert("Unable to get XmlHttpRequest");
return;
}

var u = "card-get.php?reference=" + encodeURI(ref);

x.open("GET", u, false);
x.send();

var t = x.responseText;
if (t == null || t.indexOf('=') < 0) {
alert("Unknown Customer ID [" + ref + "]");
return;
}

var ra = t.split("\n");
var lookup = new Object();
for (var i = 0; i < ra.length; i++) {
var pos = ra[i].indexOf('=');
if (pos < 0 || pos == 0) continue;

var en = ra[i].substring(0, pos);
var ev = ra[i].substring(pos + 1);

if ((en == "dob" || en == "id1_expiry") && ev.length == 10 && ev.indexOf("-") >= 0) {
ev = ev.substring(8, 10) + "/" + ev.substring(5, 7) + "/" + ev.substring(0, 4);
}

var e = EL(en);
if (e != null) e.value = ev;
}

}


so var img holds the value I need without the .jpg now I need it to display but am lost trying to make it happen.

Answer Source

Give the image tag in your html an id like

<img id="changingImage" src="pictures/thumbnails/logo-20170820013631.jpg" />

Now you can change the image source to point to the filename inside your img variable...

document.getElementById('changingImage').src="pictures/thumbnails/"+img+".jpg";