如何使用<input>时从select2获取所选文本

How to get Selected Text from select2 when using <input>

本文关键字:获取 文本 select2 何使用 input 时从      更新时间:2023-09-26

我正在使用select2控件,通过ajax加载数据。这需要使用 <input type=hidden..> 标记。

现在,我想检索所选文本。(data-bind表达式中的 value 属性仅对id进行排序)

我已经尝试过$(".select2-chosen").text(),但是当我在页面上有多个 select2 控件时,这会中断。

从 Select2 4.x 开始,它始终返回一个数组,即使对于非多选列表也是如此。

var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);

适用于 Select2 3.x 及更低版本

单选:

var data = $('your-original-element').select2('data');
if(data) {
  alert(data.text);
}

请注意,如果没有选择,变量"data"将为空。

多选:

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 文档:

data 获取或设置所选内容。类似于 val 方法,但有效 使用对象而不是 ID。

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

我终于想通了:

var $your-original-element = $('.your-original-element');
var data = $your-original-element.select2('data')[0]['text'];
alert(data);

如果还需要该值:

var value = $your-original-element.select2('data')[0]['id'];
alert(value);

用于显示文本

var data = $('#id-selected-input').select2('data'); 
data.forEach(function (item) { 
    alert(item.text); 
})

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

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

它没有记录在案,因此将来可能会在没有警告的情况下中断。

但是,您可能需要先检查是否有选择:

var s = $('.select2-chosen');
if(s.select2('data') && !!s.select2('data')[0]){
    //do work
}

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

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

下面的代码也可以解决其他问题

.on("change", function(e) {
  var lastValue = e.currentTarget.value;
  var lastText = e.currentTarget.textContent;
 });

在 Select2 版本 4 中,每个选项都具有列表中对象的相同属性;

如果你有对象

Obj = {
  name: "Alberas",
  description: "developer",
  birthDate: "01/01/1990"
}

然后检索所选数据

var data = $('#id-selected-input').select2('data');
console.log(data[0].name);
console.log(data[0].description);
console.log(data[0].birthDate);
 

我再次建议简单易行

当用户搜索并选择它时,它与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);
 });
这个

使用 V 4.0.3 工作正常

var vv = $('.mySelect2');     
var label = $(vv).children("option[value='"+$(vv).select2("val")+"']").first().html();
console.log(label); 

Select2 版本 2.4

我需要 2 个工作场景,这对我有用。

let val, 
dom = '#your_selector_id';
val = $(dom+' option:selected').text();
console.log('Initial text is '+val); 
$(document).on('change', () => {
  val = $(dom).select2('data').text;    
  console.log('Selected text is '+val);
});

检查浏览器控制台以获取调试打印。

我的下拉列表:选择2

<select id="GradeId" onchange="GetGPAByGradeId()" style="width: 100%;">
    <option value="5" selected>GPA 5</option>
    <option value="4" selected>GPA 4</option>
</select>

获取所选文本:

var _GradeId = $("#GradeId option:selected").text();
console.log(_GradeId);