Get custom data-attribute in select2 with <select>

Kalzem picture Kalzem · Mar 7, 2014 · Viewed 52.8k times · Source

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 ?

Answer

Kalzem picture Kalzem · Mar 7, 2014

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

$("#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.