IkePr
IkePr

Reputation: 930

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?

Upvotes: 2

Views: 1789

Answers (2)

Yulia T.
Yulia T.

Reputation: 151

Try this

<select id="img_change">
<option value="samsung">Samsung</option>
<option value="iphone">Apple</option>
<option value="lg">LG</option>
<option value="htc">HTC</option>

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

** jQuery code **

jQuery(document).ready(function($){

$('#img_change').on('change', function(){

        var img_path = 'someDir/' + $(this).val() + '.jpg';
        $('#changePictureYo').attr( 'src', img_path );
});

});

Upvotes: 0

R3tep
R3tep

Reputation: 12854

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";
  }
}

Upvotes: 4

Related Questions