Advertisement
Advertisement


On select change, get data attribute value


Question

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>
2011/12/01
1
276
12/1/2011 5:31:23 PM

Accepted 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.

2013/05/29
651
5/29/2013 12:12:06 AM

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.

2011/12/01

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

Vanilla Javascript:

this.querySelector(':checked').getAttribute('data-id')
2016/11/29

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

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

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.

2019/08/03

$('#foo option:selected').data('id');
2018/01/21

Source: https://stackoverflow.com/questions/8345666
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]