Development Tip

사용할 때 select2에서 선택한 텍스트를 얻는 방법

yourdevel 2020. 11. 19. 22:06
반응형

사용할 때 select2에서 선택한 텍스트를 얻는 방법


ajax를 통해 데이터로드 하는 select2 컨트롤을 사용하고 있습니다. <input type=hidden..>태그를 사용해야합니다 .

이제 선택한 텍스트를 검색하고 싶습니다. ( 표현식 value속성 data-bindid유일한 것입니다)

시도 $(".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'변수는 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 문서에서 :

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

또한 다음 코드를 사용하여 선택한 값을 가질 수 있습니다.

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

아래 코드는 다른 방법으로도 해결됩니다.

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

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

 });

v4부터이 작업을 수행하는 올바른 방법은 다음과 같습니다.

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

문서화되지 않았으므로 향후 경고없이 중단 될 수 있습니다.

그러나 먼저 선택 항목이 있는지 확인하고 싶을 것입니다.

var s = $('.select2-chosen');

if(s.select2('data') && !!s.select2('data')[0]){
    //do work
}

다시 간단하고 쉬운 제안

사용자가 검색하고 선택할 때 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); 

쇼 텍스트에 사용

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

참고 URL : https://stackoverflow.com/questions/19814601/how-to-get-selected-text-from-select2-when-using-input

반응형