How do I set the selectize.js option List programm

2019-03-09 17:29发布

问题:

I know how to set the optionList on Initiliaztion but how do I set it programmatically? I have an inviteList Array.

$("#select-invite").options(inviteList);

回答1:

You can use load method to set options via programmatic API. You may also want to call clear and clearOptions methods to reset selected values and old options.

Here is how to put it all together:

var selectize = $("#select-invite")[0].selectize;
selectize.clear();
selectize.clearOptions();
selectize.load(function(callback) {
    callback(inviteList);
});

Please note that inviteList should be an array of objects that have properties configured in valueField and labelField options when select was initialized. For example, here is how inviteList should look like with default valueField and labelField options:

var inviteList = [
    {
        text: 'Option One',
        value: 1
    },
    {
        text: 'Option Two',
        value: 2
    }
];


回答2:

As far as I know there's no method for adding multiple options through the API. You'll need to write a loop that uses the addOption() method. You'll need to get the control instance of selectize before trying to use the API. Take a look at the example below, from the Github examples:

// Create the selectize instance as usual 
var $select = $('#select-tools').selectize({
    maxItems: null,
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    options: [
        {id: 1, title: 'Spectrometer', url: 'http://en.wikipedia.org/wiki/Spectrometers'},
        {id: 2, title: 'Star Chart', url: 'http://en.wikipedia.org/wiki/Star_chart'},
        {id: 3, title: 'Electrical Tape', url: 'http://en.wikipedia.org/wiki/Electrical_tape'}
    ],
    create: false
});

// Get the selectize control instance
var control = $select[0].selectize;

// Add the new option when a button is clicked
// Remove the click event and put the addOption call in a loop
$('#button-addoption').on('click', function() {
        control.addOption({
        id: 4,
        title: 'Something New',
        url: 'http://google.com'
    });
});

From the Github examples.