如何为selectize.js输入设置一个值? [英] How to set a value for a selectize.js input?
问题描述
我有一个表单,我想将一些默认值复制到输入中。表单输入使用selectize.js插件。我想以编程方式设置一些表单值。这样做的标准方式:
$ $ p $ $ $ $ $我的输入.val(我的默认值);
不起作用。
我有($#
$ b
var $ select = $(#my_input)。selectize() ;
var selectize = $ select [0] .selectize;
selectize.setValue(我的默认值);
有什么想法?这很容易:)我错过了它。 检查 API文档
方法 addOption(data)
和 setValue(value)
可能是您要查找的内容。
更新:查看此答案的受欢迎程度,以下是一些基于评论/请求的额外信息...
setValue(value,silent)
&emsp ;
将所选项目重设为给定值。
如果 silent 是真实的(即:true
,1
),将被触发原始输入。
addOption(data)
> 添加一个可用选项或一系列选项。如果它已经存在,什么都不会发生。
注意:这不会刷新选项列表下拉菜单(使用refreshOptions()
)。
响应选项被覆盖:
这可以通过重新初始化select而不使用您最初提供的选项。如果您不打算重新创建元素,只需将选择对象存储到变量中:
// // 1.仅设置下面的变量一次(理想情况下)
var $ select = $('select')。selectize(options); //初始化选择控制
var selectize = $ select [0] .selectize; //将选择对象存储到一个变量中(名称为selectize)
// 2.稍后使用方法访问selectize对象,例如:
selectize.addOption(data) ;
selectize.setValue('something',false);
//附注:
//您可以使用
将变量设置为之前的选项var old_options = selectize.settings;
//如果你打算调用$('select')。selectize(old_options)或者某事
I have a form from which I would like to copy some default values into the inputs. The form inputs are using the selectize.js plugin. I would like to set some of the form values programatically. The standard way of doing this:
$("#my_input").val("My Default Value");
does not work.
I have tried something like this but it does not work either.
var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue("My Default Value");
Any ideas? It's got to be easy :) I'm missing it.
Check the API Docs
Methods addOption(data)
and setValue(value)
might be what you are looking for.
Update: Seeing the popularity of this answer, here is some additional info based on comments/requests...
setValue(value, silent)
Resets the selected items to the given value.
If "silent" is truthy (ie:true
,1
), no change event will be fired on the original input.
addOption(data)
Adds an available option, or array of options. If it already exists, nothing will happen.
Note: this does not refresh the options list dropdown (userefreshOptions()
for that).
In response to options being overwritten:
This can happen by re-initializing the select without using the options you initially provided. If you are not intending to recreate the element, simply store the selectize object to a variable:
// 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
这篇关于如何为selectize.js输入设置一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!