选择2允许重新选择相同的值

时间:2016-04-08 16:54:00

标签: jquery multiple-select select2

我正在使用Select2(v3.5.2)并尝试允许用户从多个下拉列表中选择一个或多个值。

想象一下这个简单的伪html标记:

<select class='select2' multiple>
 <option value="A">A</option>
 <option value="B">B</option>
 <option value="C">C</option>
</select>

和jQuery:

$(document).ready(function() {
  $('.select2').select2();
});

默认功能只允许选择选项(A,B,C)一次,在我的场景中,我需要用户能够多次选择相同的选项,以便可以实现以下选项:

A,A,A,B,C
A,B,B,B,C,C
A,A,A,B,B,C,C,C
etc...

从我的搜索开始,它似乎不受版本3.5.2支持,但有些帖子提到版本4.0.x支持它。

但是,我找不到任何关于v4的文档,而且我还是宁愿不升级到4。

有谁知道如何使其适用于版本3(或4)?

2 个答案:

答案 0 :(得分:3)

正如您所提到的,似乎在版本4.0中修复了选择多个类似值的功能,但我在文档中找不到对它的引用。所以我必须使用// Add a listener for port connections chrome.runtime.onConnect.addListener(function(port) { // If there is a 'getCoins' connection coming in... if(port.name == "getCoins") { // ...add a listener that is called when the other side posts a message on the port. port.onMessage.addListener(function(msg) { port.postMessage(_playerCoins); }); } } 3.2v框架编写功能。 如果你仔细观察渲染的DOM,你会发现select2基本上添加了类select2,并在你从下拉列表中选择一个项目时移除了类select2-disabled,所以交易是添加select2-result-selectable回来。

select2-result-selectable

工作示例:https://jsfiddle.net/DinoMyte/qcgvucnz/1/

答案 1 :(得分:0)

我找到了 4.0 的解决方案。这个解决方案不是最好的,但它是有效的。抱歉我的英语不好!

 $("#periodos").on("select2:select",function(e){    
    e.preventDefault();
    let limite_periodos        = $("#schemas").val().length;
    var element                = e.params.data.element;
    var $element               = $(element);
    $element.detach();
    $(this).append($element);
    $(this).trigger("change");              
    $("#periodos").append('<option value="'+e.params.data.text+'">' +e.params.data.text + '</option>');
    $('#periodos').trigger('select2:close');
    return true;
}); 
$('#periodos').on('select2:unselect',function(event){
    var detect                 = false;
    var element                = event.params.data.text;            
    var selections             = $('#periodos').select2('data');
    var el                     = event.params.data.element;
    var $el                    = $(el);
    $el.detach();
}); 
$('#periodos').on('select2:close',function(event){  
    var select = document.getElementById("periodos");
    var options = [];           
    document.querySelectorAll('#periodos > option').forEach(
      option => options.push(option)
    );          
    while (select.firstChild) {
        select.removeChild(select.firstChild);
    }   
    options.sort((a, b) => parseInt(a.innerText)-parseInt(b.innerText));        
    for (var i in options) {
        select.appendChild(options[i]);
    }           
});

enter image description here

相关问题