【问题标题】:select2 jQuery plugin: get the text values of the selected options? [duplicate]select2 jQuery插件:获取所选选项的文本值? [复制]
【发布时间】:2015-08-20 16:50:40
【问题描述】:

使用了不起的jQuery select2 plugin 和Ajax 数据源,我想知道如何获取所选选项的文本值。

使用普通的select 元素我会做这样的事情:

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

但这不适用于select2,因为由 Ajax 调用填充的 <option> 值没有文本。

同时,按照文档中的建议使用 .val() 来获取所选值只会返回一个 ID 数组,而不是显示元素的文本。

有没有办法解决这个问题?

JSFiddle 这里演示问题:http://jsfiddle.net/vfa4831b/8/

【问题讨论】:

标签: jquery jquery-select2


【解决方案1】:

您可以将它们存储在一个对象中,然后像这样再次检索:

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

【讨论】:

    猜你喜欢
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2016-12-25
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多