我正在尝试将解决方案复制到this question,但没有运气。我需要向已经初始化的selectize
元素添加一个新的选择选项,该元素可能已经或可能没有将其列为<item>
选项。我的代码:
<select class="form-control pickerSelectClass" id="countries"></select>
<button type="button" onclick="addFiji();">Add "Fiji"</button>
<script>
function addFiji(){
var selectElement = $('#countries').eq(0);
var selectize = selectElement.data('selectize');
if (!!selectize) selectize.setValue("Fiji");
alert('Nothing happens. How can we add Fiji?');
}
var countries = [{"name":""}, {"name":"Afghanistan"}, {"name":"Belgium"}, {"name":"China"},{"name":"Denmark"}, {"name":"Estonia"}, {"name":"Finland"}, {"name":"Greece"}];
$.ajax({
url: '/echo/json/',
type: 'POST',
dataType: 'json',
data: { json: JSON.stringify(countries) },
error: function(err) { console.log(err); },
success: function(options) {
$('#countries').selectize({
valueField: 'name',
labelField: 'name',
searchField: 'name',
maxItems: 3,
preload: true,
options: options,
create: false,
});
}
});
</script>
答案 0 :(得分:1)
这有效(这里是Fiddle):
function addFiji()
{
var $select = $('#countries').selectize();
var selectize = $select[0].selectize;
selectize.addOption({"name":"Fiji"});
selectize.addItem('Fiji');
selectize.refreshOptions();
}