问题描述
我正在使用select2控件,通过ajax 。这需要使用< input type = hidden ..>
标记。
I am using the select2 control, loading data via ajax. This requires the use of the <input type=hidden..>
tag.
现在,我想要检索所选文本。 ( data-bind
表达式中的值
属性sotres id
only)
Now, I want to retrieve the selected text. (The value
property in the data-bind
expression sotres the id
only)
我试过 $(。select2-chosen)。text()
,但是当我在页面上有多个select2控件时,这会中断。
I have tried $(".select2-chosen").text()
, but this breaks when I have multiple select2 controls on the page.
推荐答案
从Select2 4.x开始,它总是返回一个数组,即使是非多选列表。
As of Select2 4.x, it always returns an array, even for non-multi select lists.
var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);
对于Select2 3.x及更低
For Select2 3.x and lower
单选:
var data = $('your-original-element').select2('data');
if(data) {
alert(data.text);
}
请注意,如果没有选择,变量'data'将为null 。
Note that when there is no selection, the variable 'data' will be null.
多选:
var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);
alert(data[1].text);
alert(data[1].id);
来自3.x :
在具有未设置值的单选项上调用的数据方法将返回
null,而在空的multi-select上调用的数据方法将返回
[]。
data method invoked on a single-select with an unset value will return null, while a data method invoked on an empty multi-select will return [].
这篇关于如何在使用< input>时从select2获取所选文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!