【问题标题】:Populate select2 dropdown dynamically动态填充 select2 下拉列表
【发布时间】:2023-04-03 06:01:01
【问题描述】:

我正在使用 select2 版本 3.5.4。 我想并排放置两个 select2 下拉菜单。当页面第一次加载时,一个 select2 下拉列表有数据,而第二个 select2 下拉列表为空。一旦用户单击第一个 select2 下拉列表中的条目/选项,应该对服务器进行 ajax 调用,第二个 select2 下拉列表应该填充 ajax 响应数据。我无法实现它。每当我尝试填充第二个下拉列表时,我都会遇到类似的错误,

Option 'data' is not allowed for Select2 when attached to a <select> element

Option 'ajax' is not allowed for Select2 when attached to a <select> element    

我的代码是这样的,

HTML:-

<div class="form-group">
                    <label class="col-md-4 control-label" for="folderSelect">Files & Folders</label>
                    <div class="col-md-5">
                        <div class="select2-wrapper">
                            <select class="form-control select2" id="folderSelect" name="folderSelect">
                                <option></option>
                                <option th:each="folder : ${folders}" th:value="${folder}" th:text="${folder}"/>
                            </select>
                        </div>
                    </div>

                    <div class="col-md-5">
                        <div class="select2-wrapper">
                            <select class="form-control select2" id="fileSelect" name="fileSelect">
                                <option></option>
                                <option th:each="file: ${files}" th:value="${file}" th:text="${file}"/>
                            </select>
                        </div>
                    </div>
</div>

JS:-

$('#folderSelect').on("select2-selecting", function(e) { 
           var value = $(e.currentTarget).find("option:selected").val();
           var data = null;
           $.ajax({url: "test?value=" + value, success: function(result){
             data = result;
             return result;
            }});


           $("#fileSelect").select2({
               /* ajax: { // Tried but didn't work
                    dataType: 'json',
                    url: 'test',
                    results: function (data) {
                        return {results: data};
                    }              
                }*/
               /*data: function() { //Tried but didn't work
                        $.ajax({url: "test", success: function(data){
                           return data;
                        }});
                }*/
            });

//Tried but didn't work <br>
               $("#fileSelect").select2('destroy').empty().select2({data: data});

            });

【问题讨论】:

  • 这是一个已知问题,但有一种解决方法。您本可以搜索错误并在第一个结果中得到答案。下次试试吧,谷歌是你的朋友。
  • 我用谷歌搜索了很多。解决方法类似于添加隐藏的输入字段。但老实说,我没有得到它
  • 你用的是什么版本?
  • 我使用的是 3.5.4
  • 使用版本 4.*

标签: javascript jquery jquery-select2


【解决方案1】:

关注这个

$("#fileSelect").empty();
$("#fileSelect").select2({data: data});

在我的情况下效果很好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-26
    • 2015-12-11
    • 2019-06-06
    • 2014-03-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    相关资源
    最近更新 更多