Reputation: 173
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
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")));
});
Upvotes: 1