[jquery] 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>

This question is related to jquery

The answer is


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.


By using this you can get the text, value and data attribute.

<select name="your_name" id="your_id" onchange="getSelectedDataAttribute(this)">
    <option value="1" data-id="123">One</option>
    <option value="2" data-id="234">Two</option>
</select>

function getSelectedDataAttribute(event) {
    var selected_text = event.options[event.selectedIndex].innerHTML;
    var selected_value = event.value;
    var data-id = event.options[event.selectedIndex].dataset.id);    
}

You can use context syntax with this or $(this). This is the same effect as find().

_x000D_
_x000D_
$('select').change(function() {_x000D_
    console.log('Clicked option value => ' + $(this).val());_x000D_
    <!-- undefined console.log('$(this) without explicit :select => ' + $(this).data('id')); -->_x000D_
    <!-- error console.log('this without explicit :select => ' + this.data('id')); -->_x000D_
    console.log(':select & $(this) =>    ' + $(':selected', $(this)).data('id'));_x000D_
    console.log(':select & this =>       ' + $(':selected', this).data('id'));_x000D_
    console.log('option:select & this => ' + $('option:selected', this).data('id'));_x000D_
    console.log('$(this) & find =>       ' + $(this).find(':selected').data('id'));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
    <option data-id="1">one</option>_x000D_
    <option data-id="2">two</option>_x000D_
    <option data-id="3">three</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

As a matter of microoptimization, you might opt for find(). If you are more of a code golfer, the context syntax is more brief. It comes down to coding style basically.

Here is a relevant performance comparison.


$('#foo option:selected').data('id');

document.querySelector('select').onchange = function(){   
   alert(this.selectedOptions[0].getAttribute('data-attr')); 
};

Vanilla Javascript:

this.querySelector(':checked').getAttribute('data-id')

this works for me

<select class="form-control" id="foo">
    <option value="first" data-id="1">first</option>
    <option value="second" data-id="2">second</option>
</select>

and the script

$('#foo').on("change",function(){
    var dataid = $("#foo option:selected").attr('data-id');
    alert(dataid)
});