Reputation: 177
I am trying to load data for jQuery plugin Selectize.js via ajax, but I am not able to delete options loaded with previous calls from dropdown element.
I am stuck with this code where I am able to load data via ajax and show them in dropdown, but I would like to delete them when dropdown is closed (because also typed text is deleted) and load a new ones from another ajax call (after new text is typed), but commands clearOptions(true) / refreshItems()
does not delete anything. I would like to delete only items in dropdown. If any item is selected, it should stay so.
EDIT: Based on the comments below I've updated sample code here. The current state is: items are properly loaded as options to dropdown, dropdown stays opened when data are loaded and typed text is not deleted after blur.
Only issue to solve (so far) is that when I type "something", data are loaded properly via ajax, then I select any option. It is just fine yet. But when I type "another", previous options from dropdown are deleted (that is correct), but also selected option is deleted (not correct). I understand why is that happened (selected options are deleted because options from dropmenu are deleted), but I do not have any idea how to solve it.
var selectize = $('#selectize').selectize({
sortField: 'text',
loadThrottle: 500,
onFocus: function() {
if (this.items[0] == '0') {
this.clear();
}
},
load: function(query, callback) {
if (!query.length || query.length < 2) return callback();
selectize[0].selectize.clearOptions();
selectize[0].selectize.renderCache = {};
var value = selectize[0].selectize.currentResults.query;
var ajax = [{'value': '31', 'text': 'aaa yyy'}, {'value': '32', 'text': 'aaa xxx'}, {'value': '33', 'text': 'aaa zzz'}]; // simulation of loading data via ajax
callback(ajax);
// without those two lines I was not able to open dropdown menu after loading new options, IDKW
selectize[0].selectize.blur();
selectize[0].selectize.focus();
// without this line I've lost typed text when loading new options to dropdown
setTimeout(function() {
selectize[0].selectize.setTextboxValue(value);
}, 100);
}
});
Upvotes: 1
Views: 148
Reputation: 568
Try this way:
$('#selectize').selectize({
valueField: 'value',
labelField: 'text',
searchField: 'text',
persist: false,
loadThrottle: 500,
load: function(query, callback) {
if (!query || query.length < 2) return callback();
var self = this;
var currentValue = query;
var selected = this.items;
this.clearOptions();
this.addOption(selected);
$.ajax({
url: 'api-endpoint',
type: 'GET',
data: { q: query },
success: function(res) {
callback(res);
// Maintain dropdown state and input value
setTimeout(function() {
self.blur();
self.focus();
self.setTextboxValue(currentValue);
}, 50);
},
error: function() {
callback();
}
});
},
onBlur: function() {
this.clearOptions(false);
}
});
Upvotes: 0