我正在尝试使用 selectize.js 库。在 document.ready 上,我进行 ajax 调用并获取要添加到选择列表中的选项。
这是选择标签的 html
<select id="select-country-field" name="country-field-list[]" multiple class="demo-default" style="width:50%" placeholder="Select a state...">
<option value="">Select ...</option>
</select>
这是我如何在 $(document).ready 上添加选项
var $select = $(document.getElementById('select-country-field')).selectize(options);
var selectize = $select[0].selectize;
selectize.addOption({value:1,text:'foo'});
selectize.addItem(1);
selectize.refreshOptions();
我查看了以下问题,但没有得到解决 Selectize.js manually add some items
有什么帮助吗?
最佳答案
您可以将 ajax 调用移动到 selectize load 方法中,如下所示:
$('#select-country-field').selectize({
valueField: 'country',
labelField: 'country',
searchField: 'country',
options: [],
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: 'http:// ajax-call-url',
type: 'GET',
dataType: 'json',
data: {
country: query,
},
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
}
});
'http://ajax-call-url' 应该返回这样的数组:
[{ country: 'USA'}, {country: 'GB'}, {country: 'FR'}, ... ]
关于selectize.js 动态添加选项以进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29565024/