jQuery 使用 <input> 时如何从 select2 中获取选定文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19814601/
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
How to get Selected Text from select2 when using <input>
提问by robasta
I am using the select2 control, loading datavia ajax. This requires the use of the <input type=hidden..>
tag.
我正在使用 select2 控件,通过 ajax加载数据。这需要使用<input type=hidden..>
标签。
Now, I want to retrieve the selected text. (The value
property in the data-bind
expression sotres the id
only)
现在,我想检索选定的文本。(表达式中的value
属性data-bind
sotres the id
only)
I have tried $(".select2-chosen").text()
, but this breaks when I have multiple select2 controls on the page.
我试过$(".select2-chosen").text()
,但是当我在页面上有多个 select2 控件时,这会中断。
回答by Moeri
As of Select2 4.x, it always returns an array, even for non-multi select lists.
从 Select2 4.x 开始,它总是返回一个数组,即使对于非多选列表也是如此。
var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);
For Select2 3.x and lower
对于 Select2 3.x 及更低版本
Single select:
单选:
var data = $('your-original-element').select2('data');
if(data) {
alert(data.text);
}
Note that when there is no selection, the variable 'data' will be null.
请注意,当没有选择时,变量 'data' 将为空。
Multi select:
多选:
var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);
alert(data[1].text);
alert(data[1].id);
From the 3.x docs:
从 3.x文档:
data Gets or sets the selection. Analogous to val method, but works with objects instead of ids.
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 [].
data 获取或设置选择。类似于 val 方法,但适用于对象而不是 id。
在具有未设置值的单选上调用的数据方法将返回 null,而在空多选上调用的数据方法将返回 []。
回答by Sol
I finally figured it out doing this:
我终于想通了这样做:
var $your-original-element = $('.your-original-element');
var data = $your-original-element.select2('data')[0]['text'];
alert(data);
if you also want the value:
如果您还想要该值:
var value = $your-original-element.select2('data')[0]['id'];
alert(value);
回答by Lokesh Das
Also you can have the selected value using following code:
您也可以使用以下代码获得选定的值:
alert("Selected option value is: "+$('#SelectelementId').select2("val"));
回答by RahmanRezaee
Used this for show text
用于显示文本
var data = $('#id-selected-input').select2('data');
data.forEach(function (item) {
alert(item.text);
})
回答by César Augusto
The code below also solves otherwise
下面的代码也解决了其他问题
.on("change", function(e) {
var lastValue = e.currentTarget.value;
var lastText = e.currentTarget.textContent;
});
回答by rynop
The correct way to do this as of v4 is:
从 v4 开始,正确的方法是:
$('.select2-chosen').select2('data')[0].text
$('.select2-chosen').select2('data')[0].text
It is undocumented so could break in the future without warning.
它没有记录,因此将来可能会在没有警告的情况下中断。
You will probably want to check if there is a selection first however:
但是,您可能需要先检查是否有选择:
var s = $('.select2-chosen');
if(s.select2('data') && !!s.select2('data')[0]){
//do work
}
回答by Qullbrune
This one is working fine using V 4.0.3
这个使用 V 4.0.3 工作正常
var vv = $('.mySelect2');
var label = $(vv).children("option[value='"+$(vv).select2("val")+"']").first().html();
console.log(label);
回答by Vaimeo
Again I suggest Simple and Easy
我再次建议简单易行
Its Working Perfect with ajax when user search and select it saves the selected information via ajax
当用户搜索并选择它时,它与 ajax 完美配合,它通过 ajax 保存所选信息
$("#vendor-brands").select2({
ajax: {
url:site_url('general/get_brand_ajax_json'),
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
}).on("change", function(e) {
var lastValue = $("#vendor-brands option:last-child").val();
var lastText = $("#vendor-brands option:last-child").text();
alert(lastValue+' '+lastText);
});