89

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

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

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

General Grievance
  • 4,555
  • 31
  • 31
  • 45
robasta
  • 4,621
  • 5
  • 35
  • 53

11 Answers11

218

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

For Select2 3.x and lower

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.

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:

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

Moeri
  • 9,104
  • 5
  • 43
  • 56
  • 13
    Note that if `$('your-original-element')` is set to multiple selection `$('your-original-element').select2('data')` will return array in this case `data.text` will not work instead use `data[index].text` – tangobee Aug 06 '14 at 11:57
  • 8
    With current version(v4.0.0 as of today) of select2, even for single select, only `var data = $('your-original-element').select2('data')[0]` worked for me. `$('your-original-element').select2('data').id // or .text` gave me `undefined`. See [this jsfiddle](http://jsfiddle.net/18xua31f/) for proof. Try logging `$('your-original-element').select2('data').id // or .text` in console in fiddle. – Fr0zenFyr Sep 03 '15 at 21:18
  • How to send via form submit .. normal way ? – mercury Sep 17 '16 at 19:22
  • This answer is not good. not working with 4.x + of select2. You need to go to the first item in the array like @Fr0zenFyr said. – Nicolas Belley Feb 28 '17 at 17:02
  • This `$('your-original-element').select2('data');` work for me. Thanks – always-a-learner Jun 28 '17 at 10:57
17

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);
Sol
  • 710
  • 8
  • 13
5

Used this for show text

var data = $('#id-selected-input').select2('data'); 
data.forEach(function (item) { 
    alert(item.text); 
})
Davide Casiraghi
  • 15,591
  • 9
  • 34
  • 56
Rahman Rezaee
  • 1,943
  • 16
  • 24
4

The correct way to do this as of v4 is:

$('.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
}
rynop
  • 50,086
  • 26
  • 101
  • 112
2

Also you can have the selected value using following code:

alert("Selected option value is: "+$('#SelectelementId').select2("val"));
Prasad Jadhav
  • 5,090
  • 16
  • 62
  • 80
Lokesh Das
  • 423
  • 5
  • 9
2

The code below also solves otherwise

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

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

 });
César Augusto
  • 593
  • 1
  • 7
  • 7
1

In Select2 version 4 each option has the same properties of the objects in the list;

if you have the object

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

then you retrieve the selected data

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

Again I suggest Simple and Easy

Its Working Perfect with ajax when user search and select it saves the selected information via 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);
 });
Vaimeo
  • 1,078
  • 9
  • 14
0

This one is working fine using V 4.0.3

var vv = $('.mySelect2');     
var label = $(vv).children("option[value='"+$(vv).select2("val")+"']").first().html();
console.log(label); 
Qullbrune
  • 1,925
  • 2
  • 20
  • 20
0

Select2 version 2.4

There are 2 working scenario that I required and this is what works for me.

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

Check your browser console for the debug print.

Deviance
  • 465
  • 4
  • 9
0

My Dropdown list: Select2

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

Get Selected Text:

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