I am trying to set the value of a form when loading a page in a drop down list that loads the value through an ajax call. I was asked to use addOption in another thread for another problem, but unfortunately this parameter does not work for me, because the data identifier and data name are different in this case, and I only get Id data when rendering the form. I noticed that addOption code runs before the ajax request sends the data back.
The following are snippets of code from a project. Is there a way to set the value after the ajax request completes?
HTML
<select name="country" placeholder="Please Select Country ..."></select>
Data Population, JavaScript Code
$('[name="country"]').selectize({
valueField: 'id',
labelField: 'name',
searchField: 'name',
preload: true,
create: false,
render: {
option: function(item, escape) {
return '<div>' + escape(item['name']) + '</div>';
}
},
load: function(query, callback) {
$.ajax({
url: '/countrydata',
type: 'GET',
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
},
});
Data returned by an Ajax call
id name
1 USA
2 China
3 Japan
Below is my setup code I want to work
$('[name="country"]').selectize();
$('[name="country"]')[0].selectize.setValue(3);
Field labelField , addOption, , Id , .
var item = {};
item.id = countryName;
item.name = countryName;
$('[name="country"]')[0].selectize.addOption(item);