Reputation: 1364
I have the following HTML:
<select class="form-control select-draw">
<option data-image="20" value="1">Image A</option>
<option data-image="21" value="2">Image B</option>
</select>
I'm trying to get the values for both the value
and data-image
attributes but only the value
is returned and the value for data-image
is undefined
. I have tried to use both the attr('data-image')
and the data('image')
, both of which are returning undefined on alert. What am I doing wrong here?
$(".select-draw").change(function(){
var val = $(this).val();
var img = $(this).attr("data-image");
alert(val); //Returns the correct value
alert(img); //Returns Undefined
return;
}
Upvotes: 1
Views: 1216
Reputation: 30739
You need to use find('option:selected')
to reference the selected option for which you need the data-image
value.
$(".select-draw").change(function() {
var val = $(this).val();
var img = $(this).find('option:selected').data("image");
alert(val); //Returns the correct value
alert(img); //Returns Undefined
return;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control select-draw">
<option data-image="20" value="1">Image A</option>
<option data-image="21" value="2">Image B</option>
</select>
You can also use
data('image')
instead ofattr('data-image')
to get the value of thedata
attribute
Upvotes: 2