2

I am trying to use selectize.js library. On document.ready i make a ajax call and get the options to add into select list.

Here is the html for select tag

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

and here is how I add options on $(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();

I looked at the following question asked but that did not get it to work Selectize.js manually add some items

Any help?

Community
  • 1
  • 1
ajd
  • 121
  • 1
  • 4
  • 11

1 Answers1

5

You can just move your ajax call into selectize load method like that:

$('#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' should return array like that:

[{ country: 'USA'}, {country: 'GB'}, {country: 'FR'}, ... ]
Community
  • 1
  • 1
alemv
  • 1,088
  • 1
  • 14
  • 20
  • 6
    My ajax is returning correct data, [{"id":306,"name":"Hip Measurement"}]. But I am not sure about how to update the select options to reflect this data. Can you enlighten me please, some more information about the callback method? – Vipin Verma May 23 '16 at 12:38
  • How add new option. using this. I want to add new option to database also when showing in the list like this. https://jsfiddle.net/x60Ls055/ – Pankaj Sep 06 '17 at 13:42