Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programatically add an option to an optiongroup in selectize.js

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

like image 736
Scott Lusebrink Avatar asked Nov 09 '22 19:11

Scott Lusebrink


1 Answers

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).

like image 120
Guilherme Câmara Avatar answered Nov 14 '22 21:11

Guilherme Câmara