2015-06-05 160 views
0

使用真棒jQuery select2 plugin和一個Ajax數據源,我想知道如何獲取所選選項的文本值。select2 jQuery插件:獲取所選選項的文本值?

與正常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/

+0

http://stackoverflow.com/q/19814601/40822 – dotjoe

+0

@ dotjoe是的,這是答案。謝謝! – Richard

回答

0

您可以將它們又像存儲中的對象和檢索:

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