atp atp - 1 month ago 11
Javascript Question

Updating the src of an image through select-option

How can i change the src of an image through select-option? The img-src is a php variable and once something is selected I wanted it to change a select-option from another div

The dropdown

<option value="<?php echo $aColorName; ?>">Color Name</option>
<option value="<?php echo $anotherColorName; ?>">Color Name</option>

<img src="<?php echo $colorUrl.$aColorName ?>" />

I wanted the image source to update each time a new color is selected from the options


And a vanilla version...

<select id="selectBox">
    <option value="blue">Blue</option>
    <option value="red">Red</option>

<img id="theImg" src="" />

var selectBox = document.getElementById('selectBox');
var theImg = document.getElementById('theImg');

selectBox.addEventListener('change', function() {
    theImg.src = '/images/' + this.options[this.selectedIndex].value + '.jpg';
}, false);