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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.