atp atp - 1 year ago 74
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

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download