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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:53:22  来源:igfitidea点击:

Select2 jquery - How to get text in selectbox

javascriptjqueryjquery-select2

提问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

Select2creates a data-attribute for internal purpose, were it stores some necessary information like id,selected valueof select2instance. this can used to extract selected value.

Select2创建了一个data-用于内部用途属性,是它存储像一些必要的信息idselected valueselect2实例。这可以用来提取selected value.

Select2 Community: Each element instantiated as a select2component 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

Live Demo @ JSFiddle

现场演示@JSFiddle

Happy Coding :)

快乐编码:)

回答by DerMarcus

You can get the text value of the currently selected item by:

您可以通过以下方式获取当前所选项目的文本值:

$('#id').select2('data').text