最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Select2 Retrieving Custom Properties using JS - Stack Overflow

programmeradmin2浏览0评论

I’m trying to retrieve custom properties from the select2 controls using the method described here:

I can see it says the following:

Calling select2('data') will return a JavaScript array of objects representing the current selection. Each object will contain all of the properties/values that were in the source data objects passed through processResults and templateResult callbacks.

$('#mySelect2').select2('data');

However, my problem is that for some reason, doing the select2(‘data’) only returns the ID and Text values but does not bring back any other custom properties I set.

My ProcessResults looks like so:

    processResults: function (response) {
        if (!config.serverSide) {
            return {
                results: (response.results || []).map(function (item) {
                    return {
                        id: item[idField],
                        text: item[textField],
                        disabled: item.Disabled === true,
                        dataItem: item <== this is what i'm trying to get.
                    };
                })
            };
        } else {
            return {
                results: (response.Results || []).map(function (item) {
                    return {
                        id: item[idField],
                        text: item[textField],
                        disabled: item.Disabled === true,
                        dataItem: item <== this is what i'm trying to get.
                    };
                }),
                pagination: {
                    more: response.Pagination?.more || false
                }
            };
        }
    }

What’s interesting is that when any sort of event handlers are called, I can see the whole object show up and can also see that the dataItem is available for use.

So doing the following allows me to access my dataItem:

$('#element').on('select2:select', (e) => {
    let data = e.params.data;
    let item = data.dataItem;
});

I’ve tried multiple ways to try and extract the dataItem value using .select2(‘data’) but I just can’t seem to figure out why it doesn’t work.

Any help in figuring out how to access custom properties would be appreciated!

发布评论

评论列表(0)

  1. 暂无评论