繁体   English   中英

选择输入类型=“文本”元素

[英]Selectize for input type=“text” element

我有以下HTML / Bootstrap元素:

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

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

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

编辑:

关键是:我需要用从文档中提取的预定义值填充这些关键字字段(我实际上是在做编辑器),并且如果我使用“选择”元素而不是“输入”,则无法使用以下项设置起始值:

$('#keyword').val();

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

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

这是selectize.js的文档

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

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

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

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

//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',并且可以根据需要选择其他选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM