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

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.

The answer is


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

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

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
}

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

Also you can have the selected value using following code:

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

Used this for show text

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

The code below also solves otherwise

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

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

 });

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to knockout-2.0

How to get Selected Text from select2 when using <input> Angular.js vs Knockout.js vs Backbone.js

Examples related to jquery-select2

How can I set the initial value of Select2 when using AJAX? Dynamically add item to jQuery Select2 control that uses AJAX How to set selected value of jquery select2? Styling of Select2 dropdown select boxes How to use placeholder as default value in select2 framework How can I disable selected attribute from select2() dropdown Jquery? Select2 open dropdown on focus How to use Select2 with JSON via Ajax request? Select2() is not a function jQuery select2 get value of select tag?

Examples related to ui-select2

How to get Selected Text from select2 when using <input> How do I change selected value of select2 dropdown with JqGrid? Update select2 data without rebuilding the control set the width of select2 input (through Angular-ui directive) Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio? Can I apply the required attribute to <select> fields in HTML5? jQuery UI tabs. How to select a tab based on its id not based on index How To Get Selected Value From UIPickerView UIButton: set image for selected-highlighted state How can I pass selected row to commandLink inside dataTable or ui:repeat?