Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 476
Kalzem Avatar asked Mar 07 '14 21:03

Kalzem


3 Answers

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.

like image 143
Kalzem Avatar answered Oct 18 '22 06:10

Kalzem


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;
like image 25
Paul Avatar answered Oct 18 '22 05:10

Paul


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

});
function formatOutput (item) {
    var $state = $(item.element).data('id') + ' ' + item.text;
    return $state;
};
like image 17
Wagner Langer Avatar answered Oct 18 '22 07:10

Wagner Langer