我有一个表单,我想从中将一些默认值复制到输入中。表单输入使用 selectize.js 插件。我想以编程方式设置一些表单值。这样做的标准方法:
$("#my_input").val("My Default Value");
不起作用。
我试过类似的方法,但它也不起作用。
var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue("My Default Value");
有什么想法吗?这一定很简单 :) 我想念它。
最佳答案
检查 API Docs
方法 addOption(data)
和 setValue(value)
可能就是您要找的。p>
更新:看到这个答案的受欢迎程度,这里有一些基于评论/请求的额外信息......
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).
响应选项被覆盖:
这可以通过重新初始化选择而不使用您最初提供的选项来实现。如果您不打算重新创建元素,只需将 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
关于javascript - 如何为 selectize.js 输入设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21962124/