Get custom data-attribute in select2 with <select>

65,564

Solution 1

There is no direct method with select2, you can use a combination of select2 data and jQuery like following :

$("#example").select2().find(":selected").data("id");

First you get the select2 data then you find your selected option with jQuery and finally the data-attribute.

Solution 2

Select2 v4 relies on <select> tags instead of hidden <input> tags so it's now easier to get the selected option or options: you just refer to the original <select>. This may have also been the case with Select2 v3 but I've only used Select2 v4.

$('#example option:selected').attr('data-id')

jsfiddle demonstration

See also Get selected value in dropdown list using JavaScript?

Edit: I like this answer for general purpose data object access:

var d = $("#dropdown").select2("data");

d will be an array containing the selected item(s) as objects, so to access the id property of the first item:

var id = d[0].id;

Solution 3

$(document).ready(function() {
    $('select#myselect').select2({
        templateResult: formatOutput
    });

});
function formatOutput (item) {
    var $state = $(item.element).data('id') + ' ' + item.text;
    return $state;
};

Solution 4

After hours of trying to solve this, I have manage to pull out the attribute. I am using 3.5.4

$("#select2").select2('data').element[0].attributes[1].nodeValue

HTML

<select id="select2" name="course" class="form-control">
  <option></option>  
  <optgroup label="Alabama">  
    <option value="City 1" data-url="/alabama/city-1">City 1</option>  
    <option value="City 2" data-url="/alabama/city-2">City 2</option>  
  </optgroup>  
</select>

$("#select2").select2('data').element[0].attributes[0].nodeValue --> Value Attribute
$("#select2").select2('data').element[0].attributes[1].nodeValue --> Data-URl Attribute

Solution 5

so simple, using jquery api [tested against select2 4.x version]

$('#select').on('select2:select', function (e) {
    let id = $(e.params.data.element).data('id');
});
Share:
65,564
Kalzem
Author by

Kalzem

I like creating programs in Swift and PHP/Js when I am not playing some indie games or my piano ;) Currently playing at: Final Fantasy XIII series Eyes on: Unity Engine How to animate things in 2D, 3D on iOS @BabyAzerty Steam ID : Kalzem

Updated on August 30, 2021

Comments

  • Kalzem
    Kalzem almost 3 years

    Let's assume you have the following HTML5

    <select id="example">
        <option value="AA" data-id="143">AA</option>
        <option value="BB" data-id="344">BB</option>
    </select>
    
    $("#example").select2();
    

    How do I get the data-id from the selected option ?

  • Ugo Robain
    Ugo Robain almost 10 years
    Actually i would say that $("#example").find(":selected").data("id");
  • ikuchris
    ikuchris about 9 years
    @UgoRobain your solution works perfectly where the previous one does not work in same cases . in my case I had formatResult and formatSelection , only yours helped , thanks
  • Single Entity
    Single Entity about 7 years
    Could you explain why your answer works? Just posting code is generally not that helpful
  • Admin
    Admin about 7 years
    its on the plugin documentation. you can format the template result using a function that recives the "item" as parameter, and using "item.element", returns the element itself, so u gan get any atribute from it.
  • Luco
    Luco about 6 years
    Be cautious about this, because if you change or add one more attribute you will break it
  • saurus
    saurus over 5 years
    this does not seem to work in select2 3.5 with IE Edge (at time of writing - Jan 2019)
  • Kirill A
    Kirill A over 5 years
    $("#example").select2().find(":selected").data("id"); This will run reinitialization. Better to use @UgoRobain method
  • user2796515
    user2796515 over 4 years
    For whatever reason, this was the only method that worked for me: $('#example option:selected').attr('data-id')
  • hcontreras
    hcontreras almost 4 years
    The simplest and elegant solution when using select2:select event
  • Priyanka Ahire
    Priyanka Ahire over 3 years
    In my case, After using this solution it hit dropdown again and because of this dropdown custom UI break ..Other wise this will working properly. Thanks
  • Priyanka Ahire
    Priyanka Ahire over 3 years
    This was worked for me thanks..$('#example option:selected').data("attrName")
  • z0mbieKale
    z0mbieKale almost 3 years
    Correct answer if you are using multiple option
  • Luciano Fantuzzi
    Luciano Fantuzzi almost 3 years
    Thank you, this is the right solution for 4.x. The key was the ('data') part. In my case, it was: $(<selector>).select2('data')[0]...