How do I set the selectize.js option List programmatically

╄→гoц情女王★ 提交于 2019-12-20 09:12:47

问题


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.



来源:https://stackoverflow.com/questions/20497833/how-do-i-set-the-selectize-js-option-list-programmatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!