如何在使用< input>时从select2获取所选文本 [英] How to get Selected Text from select2 when using <input>

查看:820
本文介绍了如何在使用< input>时从select2获取所选文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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 docs


data获取或设置选择。类似于val方法,但使用对象而不是id工作

data Gets or sets the selection. Analogous to val method, but works with objects instead of ids.

在具有未设置值的单选项上调用的数据方法将返回
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 [].

这篇关于如何在使用&lt; input&gt;时从select2获取所选文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆