Alexander H
Alexander H

Reputation: 173

Jquery - background-image change with data attributes from select

What do I have to change to get it working?

When I try to access $(this).data("image"), it is undefined.

HTML

<div id="imagecontainer"></div>
     <select class="image">
      <option data-image="url(http:www.test.de/images/test1.jpg)">Image1</option>
      <option data-image="url(http:www.test.de/images/test2.jpg)">Image2</option>
      <option data-image="url(http:www.test.de/images/test3.jpg)">Image3</option>
      <option data-image="url(http:www.test.de/images/test4.jpg)">Image4</option>
    </select>
</div>

jQuery:

$('.image').on('change', function() {
    $( "#imagecontainer" ).css( "background-image", ( $(this).data("image") ) );
})

Upvotes: 1

Views: 1799

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240888

The select element doesn't have a data-image attribute. The children option elements do, therefore you would have to select the selected option element:

$('option:selected', this).data("image");

or..

$(this).find('option:selected').data("image");
$('.image').on('change', function () {
    $("#imagecontainer").css("background-image", ($('option:selected', this).data("image")));
});

Example Here

Upvotes: 1

Related Questions