How to set data-* from datasources in Select2?

北慕城南 提交于 2019-12-07 02:44:31

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!