On select change, get data attribute value
Asked Answered
R

10

356

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>
Ramose answered 1/12, 2011 at 17:31 Comment(2)
Is it better to use $(this).find(':selected') or $(this).children('option:selected') ?Ramose
See this question: #648504Sweaty
S
838

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.

Sweaty answered 1/12, 2011 at 17:32 Comment(3)
i mistakenly used attr() in my inital post, i meant data() but it returns 'undefined' for me.Ramose
I've just come across this and I am wondering if the first method is preferred due to performance reasons, or another reason? @JordanBrownLovato
@Lovato my guess would be that data() is faster than attr() because attr() has to do extra work to figure what type of attribute it is. Just a guess tho.Chymotrypsin
W
45

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.

Whitmire answered 1/12, 2011 at 17:35 Comment(1)
As of 2016 find() is much faster than children() even in cases like this one where we only have a tree depth of 2.Closed
B
19
document.querySelector('select').onchange = function(){   
   alert(this.selectedOptions[0].getAttribute('data-attr')); 
};
Baber answered 30/1, 2017 at 15:17 Comment(1)
Please always endeavor to support your posted code block with explanation and/or references (even if the solution is simple / "self-explanatory") on StackOverflow because not everyone is familiar with a given language's syntax / behavior / performance.Lucullus
S
15

Maybe a more elegant way

$('option:selected', this).data('id')
Sapro answered 20/8, 2021 at 12:40 Comment(0)
M
14
$('#foo option:selected').data('id');
Melanimelania answered 21/1, 2018 at 20:51 Comment(3)
Please always endeavor to support your posted code block with explanation and/or references (even if the solution is simple / "self-explanatory") on StackOverflow because not everyone is familiar with a given language's syntax / behavior / performance.Lucullus
The OP does not have an id attribute on the select element (and doesn't need one because of the utility of this).Lucullus
this works with select2 library alsoUnrivalled
A
10

Vanilla Javascript:

this.querySelector(':checked').getAttribute('data-id')
Adulterer answered 29/11, 2016 at 12:21 Comment(2)
Please always endeavor to support your posted code block with explanation and/or references (even if the solution is simple / "self-explanatory") on StackOverflow because not everyone is familiar with a given language's syntax / behavior / performance.Lucullus
Don't know why, but no jquery solution worked, this one did :-)Diner
L
8

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.

Lucullus answered 23/4, 2018 at 23:41 Comment(0)
E
7

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)
});
Eskridge answered 6/12, 2017 at 12:22 Comment(1)
Please always endeavor to support your posted code block with explanation and/or references (even if the solution is simple / "self-explanatory") on StackOverflow because not everyone is familiar with a given language's syntax / behavior / performance.Lucullus
W
1

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);    
}
Wawro answered 17/7, 2020 at 8:42 Comment(0)
M
0
 alert($(this).first().data('id'));
Materiel answered 27/1, 2023 at 4:7 Comment(1)
Please read How to Answer and edit your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this postGlycol

© 2022 - 2024 — McMap. All rights reserved.