ReynierPM ReynierPM - 1 month ago 7
jQuery Question

How to set data-* from datasources in Select2?

I am using Select2 as follow:

$('select#fields').select2({
placeholder: 'Select a field',
data: data.fields
});


data.fields
is a JSON like this one:

"fields": [
{
"id": "companies_id",
"text": "companies_id",
"data-type": "int"
},
{
"id": "parent_companies_id",
"text": "parent_companies_id",
"data-type": "int"
},
{
"id": "client_of_companies_id",
"text": "client_of_companies_id",
"data-type": "int"
},
{
"id": "asset_locations_id",
"text": "asset_locations_id",
"data-type": "int"
},
{
"id": "companies_name",
"text": "companies_name",
"data-type": "varchar"
},
{
"id": "companies_number",
"text": "companies_number",
"data-type": "varchar"
}
]


id
and
text
are used to fill the option values, can I use the third value
data-type
and set it as an attribute for the
<option>
? If so how? Can any leave me an example?

Answer

Actually - select2 by default saves all of the attributes in the data('data') variable of the <option> element that it creates, and you can always access these values using the $(<option>).data('data'), however keep in mind that it's not the same as .data('type') for data-type="value". You need to use the complete name of the attribute.

Here is an example of how to get the value of data-type on select event:

var $example = $("#s1").select2({
    data: [
        {
            "id": "companies_id",
            "text": "companies_id",
            "data-type": "int",
            "data-extra": '1'
        },
        {
            "id": "parent_companies_id",
            "text": "parent_companies_id",
            "data-type": "int",
            "data-extra": '2'
        },
        {
            "id": "client_of_companies_id",
            "text": "client_of_companies_id",
            "data-type": "int",
            "data-extra": '3'
        },
        {
            "id": "asset_locations_id",
            "text": "asset_locations_id",
            "data-type": "int",
            "data-extra": '4'
        },
        {
            "id": "companies_name",
            "text": "companies_name",
            "data-type": "varchar",
            "data-extra": '5'
        },
        {
            "id": "companies_number",
            "text": "companies_number",
            "data-type": "varchar",
            "data-extra": '6'
        }
    ],
}).on('select2:select', function(e) {
    console.log(e.params.data['data-type'], e.params.data['data-extra']);
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
<select id="s1">
</select>