选择输入类型="文本"元件

时间:2017-10-05 07:27:25

标签: javascript jquery selectize.js

我有以下HTML / Bootstrap元素:

<div class="form-group">
  <label>Keyword:</label>
  <input type="text" class="form-control" id="keyword">
</div>

我想允许用户在使用selectize.js在此表单中键入文本时选择预定义的单词。如果未选择任何单词,则输入值为用户输入的单词。

我如何使用selectize.js做到这一点?

修改

问题是:我需要使用从文档中提取的预定义值填充这些关键字字段(我实际上正在编辑一个编辑器),如果我使用&#34;请选择&#34;元素而不是&#34;输入&#34;,我无法用:

设置起始值
$('#keyword').val();

由于这些起始值可以是随机的,因此我无法找到解决此问题的方法。

2 个答案:

答案 0 :(得分:2)

您可以在初始化时使用createcreateOnBlur选项;

以下是selectize.js

的文档

https://github.com/selectize/selectize.js/blob/master/docs/usage.md

create允许用户创建不在初始选项列表中的新项目。

createOnBlur如果为true,当用户退出该字段(在输入外点击)时,会创建并选择一个新选项(如果启用了创建设置)

答案 1 :(得分:0)

我想出了如何做到这一点:

//enable selectize on input element and add a list of options
var $select = $('#keyword').selectize({
maxItems: 1,
valueField: 'id',
labelField: 'title',
searchField: 'title',
options: [
    {id: 1, title: 'value1'},
    {id: 2, title: 'value2'},
    {id: 3, title: 'value3'}
],
create: true,
});

//store selectize object to variable
var selectize = $select[0].selectize;
//add new option and set the value to new option
selectize.addOption({id:4, title: 'value4'});
selectize.setValue(4, false);

现在加载页面后的默认选项是“value4”,可以根据需要选择其他选项。

相关问题