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

问题描述 投票:0回答:12

我有一个表单,我想将一些默认值复制到输入中。表单输入使用 selectize.js 插件。我想以编程方式设置一些表单值。执行此操作的标准方法:

$("#my_input").val("My Default Value");

不起作用。

我已经尝试过类似的方法,但它也不起作用。

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue("My Default Value"); 

有什么想法吗?这一定很容易:)我想念它。

javascript jquery html selectize.js
12个回答
89
投票

查看API文档

方法

addOption(data)
setValue(value)
可能就是您正在寻找的。


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

setValue(value, silent)

  将所选项目重置为给定值。
如果“silent”为真(即:
true
1
),则不会在原始输入上触发任何更改事件。

addOption(data)

  添加可用选项或选项数组。如果它已经存在,则不会发生任何事情。
  注意:这不会刷新选项列表下拉列表(使用
refreshOptions()
来刷新)。


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

// 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

42
投票

这对我有用:

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

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

更新:由于这个解决方案工作完美,为了使其工作,即使页面上有多个选择元素,我也更新了答案:

我们可以通过以下方式初始化:

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

在初始化后实用地设置值:

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

18
投票

简化答案:

$('#my_input').data('selectize').setValue("Option Value Here");

15
投票

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

$('#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
    });
}
});

15
投票

用户“onlyblank”的回答是正确的。一个小小的补充 - 如果需要,您可以设置 1 个以上的默认值。

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

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

6
投票

注意 setValue 仅当选择控件(例如选择字段)已经有预定义值集时才有效,对于值可以是动态的控件(例如用户可以动态添加值、文本框字段)setValue 不会起作用。

使用 createItem 函数来添加和设置选择字段的当前值

例如。

$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

6
投票

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

selectize.addOption({text: "My Default Value", value: "My Default Value"});
selectize.setValue("My Default Value"); 

2
投票

我遇到了同样的问题 - 我正在使用 Selectize 和 Rails 并想要选择关联字段 - 我希望关联记录的名称显示在下拉列表中,但我需要每个选项的值是记录,因为 Rails 使用

value
来设置关联。

我通过将

@valueAttr
的咖啡脚本变量设置为每个对象的
id
并将
@dataAttr
变量设置为记录的
name
来解决这个问题。然后我浏览了每个选项并设置:

 opts.labelField = @dataAttr
 opts.valueField = @valueAttr

它有助于查看完整的差异:https://github.com/18F/C2/pull/912/files


1
投票

我也有类似的问题。我的数据是由远程服务器提供的。我想在选择框中输入一些值,但事先不确定该值在服务器上是否有效。

所以我希望在框中输入值,并且我希望选择显示可能的选项,就像用户输入了值一样。

我最终使用了这个 hack(它可能不受支持):

var $selectize = $("#my_input").selectize(/* settings with load*/);
var selectize = $select[0].selectize;
// get the search from the remote server
selectize.onSearchChange('my value');
// enter the input in the input field
$selectize.parent().find('input').val('my value');
// focus on the input field, to make the options visible
$selectize.parent().find('input').focus();

1
投票
var $select = $(document.getElementById("selectTagName"));
var selectize = $select[0].selectize;
selectize.setValue(selectize.search("My Default Value").items[0]);

0
投票

首先加载选择下拉列表,然后选择它。 它将与普通的 $(select).val() 一起使用。


0
投票

这是最简单、最快的方法:

$('select[name^=items]').selectize({
    items: ['item1'],        //  Selected  Items
    options: [               //  Preset    Items
        {'value' => 'item1', 'text' => 'item1'},
        {'value' => 'item2', 'text' => 'item2'}
    ],
});
© www.soinside.com 2019 - 2024. All rights reserved.