Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an HTML5 data value from a select option?

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">
like image 821
dcolumbus Avatar asked Aug 26 '12 00:08

dcolumbus


1 Answers

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");
like image 140
jAndy Avatar answered Oct 16 '22 15:10

jAndy