【问题标题】:select2 can i show the default list of options in the select2 ajax callselect2 我可以在 select2 ajax 调用中显示默认选项列表吗
【发布时间】:2015-04-29 06:34:43
【问题描述】:

如何在 select2 ajax 调用插件中显示默认选项列表。

在输入字符之前,我想在下拉列表中显示至少 10 个选项。

$(".doctor_id_pat1").select2({
            placeholder: "Search Users",
            minimumInputLength: 0,
            ajax: {
                url: "test.php",
                dataType: 'json',
                data: function (term) {
                    return {
                        q: term
                    };
                },
                results: function (data, page) {

                    console.log(data);

                    return { 

                            results: $.map(data, function (item) {
                                return {
                                    text: item.text,
                                    id: item.id
                                }
                            })



                    };
                }
            }
            });

【问题讨论】:

    标签: jquery jquery-select2


    【解决方案1】:

    Select2 为您提供可自定义的选择框,支持搜索、标记、远程数据集、无限滚动和许多其他高度使用的选项。

    HTML

    <input type="hidden" id="select" value="" style="width:300px;" /><br />
    

    JAVASCRIPT

    var DEFAULT_OPTIONS = [
        { id: 'def1', text: 'Default Choice 1' },
       //your options goes here
    ];
    
    var AJAX_OPTIONS = [
        { id: '1', text: 'Choice 1' },
      //your options goes here
    ];
    
    var lastOptions = DEFAULT_OPTIONS;
    
    $('#select').select2({
        minimumInputLength: 0,
        query: function(options) {
            if (options.term) {
                $.ajax({
                    type: 'post',
                    url: '/echo/json/',
                    dataType: 'json',
                    data: {
                        json: JSON.stringify(AJAX_OPTIONS),
                        delay: 0.3
                    },
                    success: function(data) {
                        lastOptions = data;
                        options.callback({ results: data });
                    }
               });
            } else {
                options.callback({ results: lastOptions });
            }
        }
    });
    

    摆弄here

    【讨论】:

    • 但我认为,在 4.0 版中,输入 type="hidden" 已被弃用
    【解决方案2】:

    在您想要打开 select2 的 jquery 中设置此代码,

    $(".doctor_id_pat1").select2('open');
    

    您可以通过添加此代码来添加默认选项, 制作这个对象,

    var DEFAULT_OPTIONS = [
        { id: 'def1', text: 'Default Choice 1' },
       //your options goes here
    ];
    

    将此对象传递为

    $(".doctor_id_pat1").select2('data',DEFAULT_OPTIONS );

    【讨论】:

    • 这只是打开列表框,但不显示列表选项。
    猜你喜欢
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多