Reputation: 910
I have a form select with some options. The options have the atribute "data-image". When i try to catch the data value on .change of select, the return send me "undefined".
HTML
<select id="onde">
<option value="1000" data-image="SP">Sampa</option>
<option value="2000" data-image="RJ">Rio</option>
</select>
jQuery
$("#onde").change(function(){
var value = $(this).data("image");
alert(value);
});
The alert return "undefined". When I change the .data()
for .val()
, returns the value of the option (1000 or 2000), and why don't return the data-image with data?
Upvotes: 0
Views: 109
Reputation: 6694
Or you can do this way:
$('select').on('change', function(){
var value = $('#onde :selected').data("image");
alert(value);
});
Upvotes: 0
Reputation: 135
Works fine..
JS:
$("#onde").change(function(){
var value = $(this[this.selectedIndex]).data("image");
alert(value);
});
Upvotes: 0
Reputation: 388416
You need to find the selected option
var value = $(this).find('option:selected').data("image");
In the change handler this
refers to the select
element which does not have the data-image
attribute, so you need to find the selected(using :selected selector) option first then its data value
Upvotes: 2