selectize.js 向 select 动态添加选项
selectize.js dynamically adding options to select
我正在尝试使用 selectize.js 库。在 document.ready 上,我进行了 ajax 调用,并获得了要添加到 select 列表中的选项。
这是 select 标签的 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 加载方法中:
$('#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' 应该 return 这样的数组:
[{ country: 'USA'}, {country: 'GB'}, {country: 'FR'}, ... ]
我正在尝试使用 selectize.js 库。在 document.ready 上,我进行了 ajax 调用,并获得了要添加到 select 列表中的选项。
这是 select 标签的 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 加载方法中:
$('#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' 应该 return 这样的数组:
[{ country: 'USA'}, {country: 'GB'}, {country: 'FR'}, ... ]