Is it possible to use jquery to get an html5 data attribute from a select option?
<select id="change-image">
<option value="cool" data-image="myimage.jpg">Cool</option>
</select>
$("#pet-tag-id").change(function() {
var src = $("#change-image").data("image");
$("#image-preview").attr("src", src);
});
<img id="image-preview">
Yes.
You even did it in the correct manner. jQuery will pull HTML5 data attributes into its internal expando data object for elements. So you can access them just by name.
The only thing that is incorrect is, that you don't call .data()
on the correct element. You're calling it on the <select>
, but you need to grab the selected option element. Like
var src = $("#change-image option:selected").data("image");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With