【问题标题】:How to get the name from the id in select2 combo?如何从 select2 组合中的 id 获取名称?
【发布时间】:2013-12-05 11:42:13
【问题描述】:

我有select2 ComboBox,数据是由 Ajax 加载的。我正在尝试通过从输入值(在服务器端设置)读取id 并将其设置为select2 以编程方式将默认值设置为select2

我想我应该实现initSelection()函数来解决这个问题。

这是我的代码:

HTML 输入是:

<input type="hidden" class="mySelect2" value="01" name="someName" />
值“01”在服务器上设置

JavaScript 是:

$(".mySelect2").select2({
    ajax: {
        url:"data.php",
        dataType:"json",
        data:function(term, page) {
            return {
                query:term, page: page -1
            } ;
        },
        results:function(data, page) {
            return data  
        }
    }
});

我试过了,但没用。

     $(".mySelect2").select2('val', '01');

并且发生错误:“如果未定义initSelection(),则无法调用val()”

【问题讨论】:

标签: javascript jquery jquery-select2 ui-select2


【解决方案1】:

试试这样的

        $(function(){
            $(".mySelect2").select2({
                ajax: {
                    url:"data.php",
                    dataType:"json",
                    data:function(term, page) {
                        return {
                            query:term, page: page -1
                        } ;
                    },
                    results:function(data, page) {
                        return data  
                    },

                }
            });
            $(".mySelect2").select2('data', {id:'01',text:'01'});
        })

HTML 代码

<input type="hidden" class="mySelect2" style="width:100px;" value="[{id:'01',text:'01'}]" name="someName" />

【讨论】:

  • 感谢 4 的答案,但这不是我想要的。如果可能,我需要通过 设置选定的 。换句话说,我需要从 中猜测 并选择它。
  • 我的意思是 代替 。我试过这个: $(".mySelect2").select2('val', '01');但有错误“未定义initSelection”
【解决方案2】:

使用 ajax 在 select2 控件中初始化默认值的一般前提可以通过以下方式解决:

initSelection: function (element, callback) {
        var id = $(element).val();
        if (id !== "") {
        $.ajax("data.php", {
            data: {
                id: id // return a single item from your service
            },
            dataType: "json"
        }).done(function (data) {
            var results = [];
            $.each(data, function (index, item) {
                results.push({
                    id: item.Id, // whatever your id field is
                    text: item.TextValue // whatever your text field is
                });
            });
            callback(results[0]);
        });
    }
}

我不是 PHP 人,但这应该是 ajax 请求的标准。该方法基本上假设您可以返回单个结果以及列表。

【讨论】:

  • 这是否意味着我无法从我已经由ajax 初始化的数据在本地设置select2控件中的选定项?我有义务在initSelection 中发送一个ajax 请求以获取我在预初始化数据中已经拥有的单个项目?我想知道我是否可以通过id in initSelectioncallback it 从预初始化数据中获取项目。
  • 查看您的代码,您还没有加载数据 - 当您放下选择控件时,它将延迟加载。一般来说,最好的设计是查询单个值(可忽略的有效负载),并在需要时按需获取其余数据。您也可以利用 select2 控件对分页按需加载的支持。
猜你喜欢
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多