Tom Davies
Tom Davies

Reputation: 161

Changing an image source from a select value property

I'm trying to change an image source based on the value in a drop-down menu, but for some reason the code I'm using doesn't seem to work.

html

<select id="strapOptions">
<option value="black">Black Strap</option>
<option value="white">White Strap</option>
</select>
<button type="button" onclick="chooseStrapColour()">Apply Strap</button> 

Javascript

function chooseStrapColour() {
var black = "images/straps/oxford-black.png"
var white = "images/straps/oxford-white.png"
var colourRange = document.getElementById("strapOptions").value;
document.getElementById("oxStrap").src = colourRange;
}

If I change the src = at the end of the 5th line to either 'black' or 'white' then it does change the image source url, so I suspect it's something in the 4th line that's broken it.

Upvotes: 0

Views: 67

Answers (2)

depperm
depperm

Reputation: 10746

Another option is just to append the color into the image src, like so

function chooseStrapColour() {
var colourRange = document.getElementById("strapOptions").value;
document.getElementById("oxStrap").src = "images/straps/oxford-"+colourRange+".png";
}
<select id="strapOptions">
<option value="black">Black Strap</option>
<option value="white">White Strap</option>
</select>
<button type="button" onclick="chooseStrapColour()">Apply Strap</button> 
<img src='' id='oxStrap'/>

Upvotes: 0

fuyushimoya
fuyushimoya

Reputation: 9813

After you got colourRange, its value is just "black" or "white", you need to use that to further decide the string to put to src, not that value:

function chooseStrapColour() {
   var black = "images/straps/oxford-black.png"
   var white = "images/straps/oxford-white.png"
   var colourRange = document.getElementById("strapOptions").value;
   var src = (colourRange === "white") ? white : black;
   document.getElementById("oxStrap").src = src;
}

Upvotes: 1

Related Questions