atp atp - 15 days ago 6
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

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

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


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

Answer

And a vanilla version...

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

<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);