如何获取当前选中的Selectize.js输入项的值
How to get the value of the currently selected Selectize.js input item
我想知道,我怎么能在我的Selectize.js输入中获得当前选定项目的值?我已经检查了文档,并搜索了所有与Stackoverflow相关的selectize.js,但没有发现任何我可以离开的例子。什么好主意吗?以下是我认为可以根据文档工作的内容,但却给了我Undefined is not a function
错误。
请注意代码的底部,我使用select.on('change'
;这(除了其他API方法)是我尝试过的。on change工作得很好,但不幸的是其他的都没有。
var select = $('#searchTextbox').selectize({
maxItems: 1, //Max items selectable in the textbox
maxOptions: 30, //Max options to render at once in the dropdown
searchField: ['text'], //Fields the autocomplete can search through. Example of another searchable field could be 'value'
openOnFocus: true,
highlight: true,
scrollDuration: 60, //currently does nothing; should say how many MS the dropdown and drop up animations take
create: false, //Whether or not the user is allowed to create fields
selectOnTab: true,
render: {
option: function(data, escape) {
var valueArray = [];
valueArray[0] = data.value.split(",");
var color = valueArray[0][0] == "1" ? "green" : "red";
return '<div class="option" style="color: '
+ color
+ ';">'
+ escape(data.text)
+ '</div>';
},
item: function(data, escape) {
var valueArray = [];
valueArray[0] = data.value.split(",");
var color = valueArray[0][0] == "1" ? "green" : "red";
return '<div class="option" style="color: '
+ color
+ ';">'
+ escape(data.text)
+ '</div>';
}
}
});
select.on('change', function() {
var test = select.getItem(0);
alert(test.val());
});
找到问题了!
对于任何使用selectize.js并且有API问题的人,试试这个!
如果你看一下我初始化selectize.js下拉列表的那部分代码,我将实例存储在我的'select'变量中,就是这样。然而,这不是正确的做事方式(至少从我所看到的来看)。您需要执行以下操作,而不是简单地将实例存储在变量中。
var $select = $("#yourSelector").selectize({
//options here
});
var selectizeControl = $select[0].selectize
这样做之后,就可以正确地使用API了。没有这样做,我得到一个Undefined is not a function
错误。
最后,为了回答我自己的问题,我能够通过使用以下代码(.on('change')和alert显然是不必要的)检索selectize输入的当前值:
selectizeControl.on('change', function() {
var test = selectize.getValue();
alert(test);
});
为什么有必要这样做,我不太确定。也许有人可以启发我和任何未来的观众,为什么这种方法有效,而我以前的方法没有。
我希望这能帮助别人在未来。请随意编辑和修改
您可以在初始化时添加事件,而不是稍后添加事件:
var select = $('#searchTextbox').selectize({
maxItems: 1, //Max items selectable in the textbox
maxOptions: 30, //Max options to render at once in the dropdown
...
onChange: function(value) {
alert(value);
}
});
查看文档获取更多回调。
在我的测试中,selectize立即更新它"替换"的<select>
的值(实际上它只使用display: none
隐藏<select>
)。
所以如果你不想使用回调或者全局变量,就像这样简单:
$('#id_of_the_select_element_you_called_selectize_on').val()
。
在我的情况下,上面的答案不起作用,但我想出了一个简单的解决方案。
$("select").on('change', function() {
var val = $(this).find(".item").attr('data-value');
alert(val);
});
我使用了一个input-group-button,像这样: