user1888260
user1888260

Reputation: 47

jQuery change image with select not working

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>

Upvotes: 0

Views: 264

Answers (2)

Johan Karlsson
Johan Karlsson

Reputation: 6476

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/

Upvotes: 2

Pavel Reznikov
Pavel Reznikov

Reputation: 3208

$("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/

Upvotes: 1

Related Questions