I want to dynamically add an option to an optiongroup in Selectize.js. The API only has
addOption(data)
updateOption(value, data)
addOptionGroup(id, data)
without much help on what "data" is. I've seen the examples for adding an option but no mention of using optionGroups
$('#button-addoption').on('click', function() {
control.addOption({
id: 4,
title: 'Something New',
url: 'http://google.com'
});
Thanks
Data is the object passed to the optgroup rendering method. And so, you can put anything in it.
$('#selectize').selectize({
...
optgroupField: 'mygroup',
render: {
optgroup_header: function(data, escape) {
return '<div class="optgroup-header">' + escape(data.a) + escape(data.b) '</div>';
}
},
...
});
And then, whenever you want, you can add groups and options in the selectize:
//add group
var optGroup = { a: 'fruit', b: ... };
$('#selectize')[0].selectize.addOptionGroup('0', optGroup);
//add option
var option = { value: 'abc', text: 'banana', mygroup: '1'};
$('#selectize')[0].selectize.addOption(option);
Of course, if you only want a label for the group, you can do this:
//code
...
render: {
optgroup_header: function(data, escape) {
return '<div class="optgroup-header">' + escape(data) + '</div>';
}
...
//code
$('#selectize')[0].selectize.addOptionGroup('1', 'meat');
You can see the API demo (search for 'Optgroups (programmatic)' in page).
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