向初始化的选择元素添加新选项

时间:2018-01-01 11:35:56

标签: jquery selectize.js

我正在尝试将解决方案复制到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>

请参阅jsfiddle1(和jsfiddle2了解替代方法)。这些都没有任何影响。感谢我出错的任何指针。

1 个答案:

答案 0 :(得分:1)

这有效(这里是Fiddle):

function addFiji()
{
    var $select = $('#countries').selectize();
    var selectize = $select[0].selectize;
    selectize.addOption({"name":"Fiji"});
    selectize.addItem('Fiji');
    selectize.refreshOptions();
}