How to programatically add an option to an optiongroup in selectize.js
Asked Answered
G

1

7

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

Genesisgenet answered 30/1, 2015 at 17:16 Comment(0)
S
1

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

Subtract answered 24/3, 2016 at 19:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.