ofko ofko - 6 days ago 7
jQuery Question

On select change, get data attribute value

The following code returns 'undefined'...

$('select').change(function(){
alert($(this).data('id'));
});

<select>
<option data-id="1">one</option>
<option data-id="2">two</option>
<option data-id="3">three</option>
</select>

Answer

You need to find the selected option:

$(this).find(':selected').data('id')

or

$(this).find(':selected').attr('data-id')

although the first method is preferred.

Comments