动态填充select2下拉列表

时间:2017-10-05 16:18:31

标签: javascript jquery jquery-select2

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

这样的错误
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});

            });

1 个答案:

答案 0 :(得分:0)

关注

.ruby_version

在我的情况下效果很好

相关问题