Search code examples
htmljquery-select2custom-data-attribute

Get custom data-attribute in select2 with <select>


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 ?


Solution

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