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

标签 javascript jquery html selectize.js

我有一个表单,我想从中将一些默认值复制到输入中。表单输入使用 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) 可能就是您要找的。


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

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 (use refreshOptions() 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/

相关文章:

javascript - 从具有特定值的二维数组中的行返回值 - 在 Google 脚本中以 HTML 形式列出结果

javascript - 使用 JavaScript 从 URL 中提取特定变量

jquery - JavaScript : getting td index

javascript - 无法获取下拉项的 ID

javascript - 如何创建带有 Content-Type header 的响应?

javascript - 拒绝使用亚马逊网址从 pdf.js 获取不安全 header "Accept-Ranges"错误

jquery - 设置移动幻灯片左侧菜单样式的一些问题

javascript - 如何单击具有单击事件的元素下的按钮

javascript - 如果禁用 Javascript,则使网页可见

javascript - 带按钮的 HTML5 干净 Canvas