Reputation: 121
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?
Upvotes: 2
Views: 18224
Reputation: 1096
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'}, ... ]
Upvotes: 5