使用时如何从select2获取Selected Text

时间:2022-08-10 20:34:42

I am using the select2 control, loading data via ajax. This requires the use of the <input type=hidden..> tag.

我正在使用select2控件,通过ajax加载数据。这需要使用标记。

Now, I want to retrieve the selected text. (The value property in the data-bind expression sotres the id only)

现在,我想检索选定的文本。 (data-bind表达式中的value属性仅用于id)

I have tried $(".select2-chosen").text(), but this breaks when I have multiple select2 controls on the page.

我尝试了$(“。select2-chosen”)。text(),但是当我在页面上有多个select2控件时,这会中断。

7 个解决方案

#1


120  

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'将为null。

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获取或设置选择。类似于val方法,但与对象而不是id一起使用。

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 [].

在具有未设置值的单选择上调用的数据方法将返回null,而在空多选中调用的数据方法将返回[]。

#2


12  

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);

#3


1  

Also you can have the selected value using following code:

您还可以使用以下代码获取所选值:

alert("Selected option value is: "+$('#SelectelementId').select2("val"));

#4


0  

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);
 });

#5


0  

The code below also solves otherwise

下面的代码也解决了

.on("change", function(e) {

  var lastValue = e.currentTarget.value;
  var lastText = e.currentTarget.textContent;

 });

#6


0  

The correct way to do this as of v4 is:

从v4开始执行此操作的正确方法是:

$('.select2-chosen').select2('data')[0].text

$( 'SELECT2挑选 ')。SELECT2(' 数据')[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
}

#7


0  

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); 

#1


120  

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'将为null。

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获取或设置选择。类似于val方法,但与对象而不是id一起使用。

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 [].

在具有未设置值的单选择上调用的数据方法将返回null,而在空多选中调用的数据方法将返回[]。

#2


12  

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);

#3


1  

Also you can have the selected value using following code:

您还可以使用以下代码获取所选值:

alert("Selected option value is: "+$('#SelectelementId').select2("val"));

#4


0  

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);
 });

#5


0  

The code below also solves otherwise

下面的代码也解决了

.on("change", function(e) {

  var lastValue = e.currentTarget.value;
  var lastText = e.currentTarget.textContent;

 });

#6


0  

The correct way to do this as of v4 is:

从v4开始执行此操作的正确方法是:

$('.select2-chosen').select2('data')[0].text

$( 'SELECT2挑选 ')。SELECT2(' 数据')[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
}

#7


0  

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);