0

Working with the awesome jQuery select2 plugin and an Ajax data source, I would like to know how to get the text values of the selected options.

With a normal select element I would do something like this:

$('#myselect option:selected").each(function() {
  var $this = $(this);
  if ($this.length) {
    console.log($this.val(), $this.text());
  }
});

But that doesn't work with select2, because the <option> values populated by the Ajax call have no text.

Meanwhile, using .val() as suggested in the documentation to get the selected values just returns an array of IDs, not the text of the displayed elements.

Is there any way around this?

JSFiddle here to demonstrate the problem: http://jsfiddle.net/vfa4831b/8/

Richard
  • 62,943
  • 126
  • 334
  • 542

1 Answers1

0

You can store them in an object and retrieve again like that :

var selectedValues = {}

$(".select2").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term,
      };
    },
    processResults: function (data, page) {
      return {
        results: data.items
      };
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; }, 
  minimumInputLength: 1,
  templateResult: function(repo) { 

    return repo.name + ' (' + repo.full_name + ')';
  },
   templateSelection: function(repo) { 
    selectedValues[repo.id] = repo.full_name;
    return repo.name + ' (' + repo.full_name + ')';
  }
});
$('#clickme').on('click', function() { 
    var id = $('.select2').val();
    console.log(selectedValues[id]); 
});
Özgür Ersil
  • 6,909
  • 3
  • 19
  • 29