[英]Populate select2 dropdown dynamically
我正在使用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});
});
跟隨這個
$("#fileSelect").empty();
$("#fileSelect").select2({data: data});
在我的情況下效果很好
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.