IkePr IkePr - 3 days ago 5
HTML Question

jQuery / JavaScript - Change image in another div based on select option

I have created a select option:

<select>
<option value="samsung">Samsung</option>
<option value="apple">Apple</option>
<option value="lg">LG</option>
<option value="htc">HTC</option>
</select>


Later in the code, I have:

<div class="col-lg-6 text-center"> <!-- bootstrap stuff -->
<img id="changePictureYo" src="Slike/uredjajS1.png"/>
</div>


I want the img src to change depending on the selected option. (So if I select Apple, the img src would change to Slike/iphone.png).

I have tried this:

<select>
<option value="samsung">Samsung</option>
<option value="apple" onselect="changeImage()">Apple</option>
<option value="lg">LG</option>
<option value="htc">HTC</option>
</select>


And in my
.js
file:

function changeImage() {
document.getElementById("changePictureYo").src = "Slike/iphone.png";
}


But it is not working. What am I missing?

Answer

The event onSelect is not supported by the <option> tag

The select event only fires when text inside a text input or textarea is selected. The event is fired after the text has been selected.

You need to use onChange event.

<select onchange="changeImage(this)">
  <option value="samsung">Samsung</option>
  <option value="apple">Apple</option>
  <option value="lg">LG</option>
  <option value="htc">HTC</option>
</select>

JS :

function changeImage(el) {
  if (el.value == "apple") {
    document.getElementById("changePictureYo").src = "Slike/iphone.png";
  }
}
Comments