簡體   English   中英

Select2下拉菜單在第三個所選項目上顯示“ x selected”

[英]Select2 dropdown to show “x selected” on third selected item

以下代碼使用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/

我努力工作並設法為您提供了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的源代碼。

我制造了一個小提琴 嘗試這種方式..

$("#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('');
    });
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM