我使用的是 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});
});
最佳答案
按照这个
$("#fileSelect").empty();
$("#fileSelect").select2({data: data});
在我的案例中效果很好
关于javascript - 动态填充 select2 下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46590389/