0

I am trying to do a simple image change on a dropdown, but I cannot get it working correctly for some reason, can anyone clue me in on what I am missing?

The Jsfiddle here has the code.

Thanks guys!

$("#display_avatar").change(function(){
    $("img[name=preview]").attr("src", $("option").attr("imagePath"));
    event.preventDefault();
});

<img src="http://placehold.it/100/0000FF/000000" name="preview" /><br /><br />

<select class="form-control" name="display_avatar" id="display_avatar">
    <option value="1" imagePath="http://placehold.it/100/cccccc/000000">First</option>
    <option value="2"imagePath="http://placehold.it/100/ghghgh/000000">Second</option>
    <option value="3"imagePath="http://placehold.it/100/5fgrty/000000">Third</option>
    <option value="4"imagePath="http://placehold.it/100/ff0000/000000">Fourth</option>
</select>
user1888260
  • 47
  • 2
  • 11

2 Answers2

2

This will just get the value from the first option:

$("option").attr("imagePath")

try this instead:

this.selectedOptions[0].getAttribute("imagePath")

Updated fiddle: http://jsfiddle.net/979vbv0j/2/

Johan Karlsson
  • 6,419
  • 1
  • 19
  • 28
1

$("option") returns all option on the page. To do what you want you need do like this:

$("#display_avatar").change(function(){
    $("img[name=preview]").attr("src", $(this).find("option:selected").attr("imagePath"));
    event.preventDefault();
});

Please check: jQuery Get Selected Option From Dropdown

Upd: working sample: http://jsfiddle.net/vm6zjobj/1/

Community
  • 1
  • 1
Pavel Reznikov
  • 2,968
  • 1
  • 18
  • 17