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>

Solution 1:

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.

Solution 2:

Try the following:

$('select').change(function(){
  alert($(this).children('option:selected').data('id'));
});

Your change subscriber subscribes to the change event of the select, so the this parameter is the select element. You need to find the selected child to get the data-id from.