Select2 jquery - 如何在选择框中获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16301052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select2 jquery - How to get text in selectbox
提问by DeLe
I have input text like
我输入了类似的文本
<input type="hidden" name="xa" id="xa" data-placeholder=".." style ="width: 360px;"/>
and i using select2
我使用select2
$("#xa").select2({...});
now, i want to get text when i press 'get text'
现在,我想在按“获取文本”时获取文本
$("#gettext").click(function () {
alert($('#xa').val()); // or $('#xa').select2("val");
});
But it get the id of text. It's not text. How can i do it. thanks
但它获得了文本的 id。这不是文字。我该怎么做。谢谢
采纳答案by dreamweiver
Select2
creates a data-
attribute for internal purpose, were it stores some necessary information like id
,selected value
of select2
instance. this can used to extract selected value
.
Select2
创建了一个data-
用于内部用途属性,是它存储像一些必要的信息id
,selected value
的select2
实例。这可以用来提取selected value
.
Select2 Community: Each element instantiated as a
select2
component must contain id and text keys.
Select2 Community:实例化为
select2
组件的每个元素都必须包含 id 和 text 键。
var id = $(test).select2('data').id;
var id = $(test).select2('data').id;
var seletedVal = $(test).select2('data').text;
var seletedVal = $(test).select2('data').text;
Update :With Latest version of Select2 , the object is stored in a array,so the text has to be accessed as below (jsfiddle link updated as well
).
更新:使用 Select2 的最新版本,对象存储在数组中,因此必须按如下方式访问文本(jsfiddle link updated as well
)。
$(test).select2('data')[0].text
//instead of $(test).select2('data').text
$(test).select2('data')[0].text
// 而不是 $(test).select2('data').text
thanks for update @DiMono
感谢更新@DiMono
Happy Coding :)
快乐编码:)
回答by DerMarcus
You can get the text value of the currently selected item by:
您可以通过以下方式获取当前所选项目的文本值:
$('#id').select2('data').text