2016-06-10 70 views
1

以下代碼使用select2從下拉列表中選擇多個選項。我的問題是如何在第三次選擇後顯示「x選定」,而不是所有的選擇,並有一個巨大的文本框?Select2下拉菜單在第三個選定項目上顯示「x selected」

<select multiple id="e1" style="width:300px"> 
     <option value="AL">Alabama</option> 
     <option value="Am">Amalapuram</option> 
     <option value="An">Anakapalli</option> 
     <option value="Ak">Akkayapalem</option> 
     <option value="WY">Wyoming</option> 
    </select> 

$("#e1").select2(); 

我有一個的jsfiddle這裏

http://jsfiddle.net/ishanbakshi/fyhsz9ra/

+0

你能解釋得更清楚「」x選擇「後第三選擇」所有選擇或只是第三? –

回答

1

我一直努力工作的管理提供了一個jQuery爲你解決。將您的JavaScript更改爲:

$("#e1").select2(); 

$(document).ready(function(){ 
var showHugeSelect = false; 

$("#s2id_e1 ul.select2-choices").prepend("<button id='btnE1ShowAll' style='display: none;' />") 

$("#btnE1ShowAll").click(function(e){ 
$("#s2id_e1 .select2-search-choice").show(); 
$("#btnE1ShowAll").hide(); 
showHugeSelect = true; 

function hideHugeSelect(){ 
showHugeSelect = false; 
} 

setTimeout(hideHugeSelect, 5000); 
}) 

setInterval(customizeSelectE1, 500); 

function customizeSelectE1(){ 
var selectedCount = $("#s2id_e1 .select2-search-choice").length; 

if(selectedCount > 2 && !showHugeSelect){ 
$("#s2id_e1 .select2-search-choice").hide(); 
$("#btnE1ShowAll").html(selectedCount + " selected").show(); 
} 
} 


}) 

我已經在jsFiddle中檢查過它,它完美地工作。無法制作更優雅的解決方案。如果你真的想要一個更優雅的,你需要開發自己的控制或更改Select2的源代碼。

1

我創建了一個fiddle。嘗試這種方式..

$("#e1").select2().on('change', function() { 
    if ($(this).val().length >= 3) { 
    var html = $('.select2-choices li:first-child').clone(); 
    $('.select2-choices li:not(:last-child)').remove(); 
    var divContent = html.find('div').html($(this).val().length + ' Selected'); 
    $('.select2-choices').prepend(html).find('a').on('click', function() { 
     $(this).parent('li').remove(); 
     $("#e1").val(''); 
    }); 
    } 
}); 
相關問題