2

I'm trying to replicate the solutions to this question but having no luck. I need to add a new selected option to an already-initialised selectize element that may or may not already list it as an <item> option. My code:

<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>

See jsfiddle1 (and jsfiddle2 for an alternative method). Neither of these has any effect. Grateful for any pointers where I'm going wrong.

geotheory
  • 22,624
  • 29
  • 119
  • 196
  • 1
    Did you try `add` event => `selectize.addOption(options); selectize.refreshOptions(true);` or `addItem` – Pedram Jan 01 '18 at 11:52

1 Answers1

1

This works (here is the Fiddle):

function addFiji()
{
    var $select = $('#countries').selectize();
    var selectize = $select[0].selectize;
    selectize.addOption({"name":"Fiji"});
    selectize.addItem('Fiji');
    selectize.refreshOptions();
}
Ivan86
  • 5,695
  • 2
  • 14
  • 30