簡體   English   中英

將select2下拉列表從單選轉換為多選

[英]Convert select2 dropdown from single select to multiple select

我在復雜控件中有10到12個select2下拉菜單,它們需要初始化為select2下拉菜單。
在dropdown-open上 ,我進行ajax調用以加載數據。 如果從服務器加載了特定的數據,問題就出在這里。 下拉列表應變為多個select2。

這是代碼的一部分:

$selectDropDown.select2({
    ajax: {
        url: '/GetValues',
        dataType: 'json',
        data: function (params) {
            var query = {
                title: name,
            }

            return query;
        },
        processResults: function (data) {
            if (data.type === '10') {

               // I need to make it multiple select here
               return {results: data.results};
            } else {
               var values = getDefaultDataItems();
               return {results: values };
            }

        }
    },
    allowClear: true,
    placeholder: 'Select values'
    width: '100%',
});

由於優化原因,無法在select2初始化之前加載數據。

目前它的工作方式如下:

 processResults: function (data) {
            if (data.type === '10') {

               // The hacking way
               $selectDropDown.select2({
                        multiple: 'multiple',
                        data: data.results
                    }).select2('open');
            } else {
               var values = getDefaultDataItems();
               return {results: values };
            }
        }

我想問問他最好的方法嗎?
有內置功能嗎?

對我來說,最好的方法是將屬性multiple添加到我的select 並將屬性名稱更改為數組。 之后,調用.select2(); 根據我的select

例如,我select sub-type類。

$('.sub-type').prop('multiple', true).attr('name', 'sub_type[]').select2();

如果要再次返回單選,只需編寫以下代碼:

$('.sub-type').prop('multiple', false).attr('name', 'sub_type').select2();

對不起,我今天才找到您的問題。 我希望我的回答可以幫助其他人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM