如何设置selectize.js输入的值?

fat*_*sma 56 html javascript jquery selectize.js

我有一个表单,我想从中将一些默认值复制到输入中.表单输入使用selectize.js插件.我想以编程方式设置一些表单值.这样做的标准方法:

$("#my_input").val("My Default Value");
Run Code Online (Sandbox Code Playgroud)

不起作用.

我尝试过类似的东西,但它也不起作用.

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue("My Default Value"); 
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?这很简单:)我很想念它.

Tom*_*now 69

查看API文档

方法addOption(data)setValue(value)可能是你正在寻找的.


更新:看到这个答案的受欢迎程度,这里有一些基于评论/请求的附加信息......

setValue(value, silent)
  将所选项目重置为给定值.
  如果" 沉默 "是真实​​的(即:true,1),则不会在原始输入上触发更改事件.

addOption(data)
  添加可用选项或选项数组.如果它已经存在,那么什么都不会发生.
  注意:这不会刷新选项列表下拉列表(refreshOptions()用于此).


响应被覆盖的选项:
这可以通过重新初始化选择而不使用您最初提供的选项来实现.如果您不打算重新创建元素,只需将选择对象存储到变量:

// 1. Only set the below variables once (ideally)
var $select = $('select').selectize(options);  // This initializes the selectize control
var selectize = $select[0].selectize; // This stores the selectize object to a variable (with name 'selectize')

// 2. Access the selectize object with methods later, for ex:
selectize.addOption(data);
selectize.setValue('something', false);


// Side note:
// You can set a variable to the previous options with
var old_options = selectize.settings;
// If you intend on calling $('select').selectize(old_options) or something
Run Code Online (Sandbox Code Playgroud)

  • 你的回答让我走上正轨.请注意一点:似乎setValue会默默地关闭不在列表中的选项,至少在我的测试中是这样.有关报告和jsfiddle,请参阅https://github.com/brianreavis/selectize.js/issues/568. (2认同)
  • 当您调用 $("#my_input").selectize() 时,您的原始设置(即插件、渲染函数等)将被覆盖。如何让 selectize 对象调用 setValue() 而不覆盖这些设置? (2认同)

小智 34

这对我有用:

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue(selectize.search("My Default Value").items[0].id);
Run Code Online (Sandbox Code Playgroud)

但你必须非常确定你只有一场比赛.

更新:由于此解决方案工作正常,为了使其工作即使页面上有多个选择元素我已更新答案:

按照以下方式我们可以初始化:

$('select').each(function (idx) {
    var selectizeInput = $(this).selectize(options);
    $(this).data('selectize', selectizeInput[0].selectize);
});
Run Code Online (Sandbox Code Playgroud)

初始化后实际设置值:

var selectElement = $('#unique_selector').eq(0);
var selectize = selectElement.data('selectize');
if (!!selectize) selectize.setValue("My Default Value");
Run Code Online (Sandbox Code Playgroud)


Shu*_*ham 13

用户'onlyblank'的回答是正确的.除此之外的一小部分 - 如果需要,您可以设置多个默认值.

而不是将id传递给setValue(),传递一个数组.例:

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
var yourDefaultIds = [1,2]; # find the ids using search as shown by the user onlyblank
selectize.setValue(defaultValueIds);
Run Code Online (Sandbox Code Playgroud)


VK3*_*321 8

这是我使用远程搜索标签的完整代码.希望这是有帮助的.

$('#myInput').selectize({
valueField: 'id',
labelField: 'name',
searchField: 'name',
options: [],
delimiter: ',',
persist: false,
create: false,
load: function(query, callback) {
    if (!query.length) return callback();
    $.ajax({
        url: '/api/all_cities.php',
        type: 'GET',
        dataType: 'json',
        data: {
            name: query,
        },
        error: function() {
            callback();
        },
        success: function(res) {
            callback(res);
        }
    });
},
onInitialize: function(){
    var selectize = this;
    $.get("/api/selected_cities.php", function( data ) {
        selectize.addOption(data); // This is will add to option
        var selected_items = [];
        $.each(data, function( i, obj) {
            selected_items.push(obj.id);
        });
        selectize.setValue(selected_items); //this will set option values as default
    });
}
});
Run Code Online (Sandbox Code Playgroud)


小智 8

一个简化的答案:

$('#my_input').data('selectize').setValue("Option Value Here");
Run Code Online (Sandbox Code Playgroud)


小智 6

刚刚遇到了同样的问题并用以下代码行解决了它:

selectize.addOption({text: "My Default Value", value: "My Default Value"});
selectize.setValue("My Default Value"); 
Run Code Online (Sandbox Code Playgroud)


Jpl*_*us2 5

注意setValue仅在selectize控件(例如select字段)已经有预定义的一组值时才起作用,对于那些值可以是动态的(例如用户可以在文本框字段中动态添加值)的控件来说,setValue不会工作。

使用createItem functon代替添加和设置selectize字段的当前值

例如

$selectize[ 0 ].selectize.clear(); // Clear existing entries
for ( var i = 0 ; i < data_source.length ; i++ ) // data_source is a dynamic source of data
    $selectize[ 0 ].selectize.createItem( data_source[ i ] , false ); // false means don't trigger dropdown
Run Code Online (Sandbox Code Playgroud)