我使用select2 v.3.5.1并需要选择多个项目。我想,是否可以使用shift
键选择多个项目?我不想拥有multiple select
,只需在按住shift
键时选择几个选项即可。非常感谢代码片段。
答案 0 :(得分:0)
您可以按住ctrl键进行操作。 如果您正在其他程序中的列表中选择单个项目,则按下默认键。
答案 1 :(得分:0)
如果我理解正确答案,可能的解决方案可以基于:
$(document).on('keyup keydown', ".select2-drop-active", function (e) {
console.log('shift: ' + e.shiftKey);
if (e.shiftKey) {
$("#mySelect1").attr('multiple', 'multiple');
} else {
$("#mySelect1").removeAttr('multiple');
}
})
$("#mySelect1").select2()
.on('select2-selecting', function (e) {
var maxItem = $('#mySelect1').data('maxitem');
var shiftKey = $("#mySelect1").attr('multiple') == 'multiple';
var seletedOpt = $('.select2-drop-active .mySelected').length;
console.log('maxItem: ' + maxItem + ' shiftKey: ' + shiftKey + ' seletedOpt: ' + seletedOpt);
if (shiftKey && seletedOpt < maxItem) {
$('.select2-drop-active .select2-highlighted').addClass('mySelected');
if ($('.select2-drop-active .mySelected').length >= maxItem) {
$("#mySelect1").removeAttr('multiple');
var selectedOption = $('.select2-drop-active .mySelected').map(function (idx, ele) {
return ele.textContent;
}).get().join(' ');
setTimeout(function() {
$('.select2-container a span:first').text(selectedOption);
}, 100, selectedOption);
} else {
e.preventDefault();
}
} else {
$("#mySelect1").removeAttr('multiple');
}
});
&#13;
.mySelected {
background: #3875d7;
color: #fff;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://rawgit.com/cdnjs/cdnjs/master/ajax/libs/select2/3.5.1/select2.min.css" rel="stylesheet"/>
<script src="https://rawgit.com/cdnjs/cdnjs/master/ajax/libs/select2/3.5.1/select2.min.js"></script>
<select id="mySelect1" data-maxitem="2" style="width: 100%;">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
&#13;