If you have created custom render functionality on your selectize dropdown, is it possible to refresh the dropdown items dynamically using ajax? I can do one or the other, but when I combine both parts of the functionality, the selectize dropdown items do not re-render.
I have used the callback function to set the new list of options.
The selectize control is initialized with the following javascript code when the page loads.
var $select = $(item).selectize({
create: false,
sortField: 'text',
selectOnTab: true,
valueField: 'id',
labelField: 'text',
searchFields: ['text'],
render: {
item: function(selectItem, escape) {
var splitAt = selectItem.text.indexOf(';');
var label;
var caption = '';
if (splitAt > 0) {
label = selectItem.text.substring(0, splitAt);
caption = selectItem.text.substring(splitAt + 1);
} else {
label = selectItem.text;
}
return '<div>' +
(label ? '<span class="text">' + escape(label) + '</span>' : '') +
(caption ? '<span class="description">' + escape(caption) + '</span>' : '') +
'</div>';
},
option: function(selectItem, escape) {
var splitAt = selectItem.text.indexOf(';');
var label;
var caption = '';
if (splitAt > 0) {
label = selectItem.text.substring(0, splitAt);
caption = selectItem.text.substring(splitAt + 1);
} else {
label = selectItem.text;
}
return '<div>' +
'<span class="label">' + escape(label) + '</span>' +
(caption ? '<span class="caption">' + escape(caption) + '</span>' : '') +
'</div>';
}
}
});
I then have an ajax method that requests the latest drop down options and attempts to update the selectize control:
var refreshSuppliers = function() {
$.getJSON('url/suppliers', function(results) {
if (results) {
var selectOptions = [];
for (var index = 0, length = results.length; index < length; index++) {
var item = results[index];
selectOptions.push({
text: item.Option,
value: item.Id.toString()
});
}
var selectize = $("#Supplier")[0].selectize;
selectize.clear();
selectize.clearOptions();
selectize.load(function(callback) {
callback(selectOptions);
});
}
})
Once the method runs, the dropdown on the web page is empty. If I remove all the custom rendering and treat as a simple selectize drop down, the ajax call to update the drop down works.
Is there a way for these two features to work together?
There appears to be a bug in the selectize.js library where the rendered output is not being cleared from the renderCache when you call clearOptions(). I was able to get this to work by clearing the cache manually:
selectize.clearOptions();
selectize.renderCache = {};
selectize.load(function(callback) {
callback(selectOptions);
});
There is an open issue on github for this: https://github.com/brianreavis/selectize.js/issues/260
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With