【发布时间】:2021-12-27 19:13:51
【问题描述】:
亲爱的,对于我的 select2 多选,我想显示所选项目的数量。下面的代码说明了这一点:
对于一个选定的项目: "2 选 1"
对于两个选定的项目: “2 个中的 2 个”“2 个中的 2 个”
当您选择了两个选项时,有人知道如何只显示一次文本吗?
<!DOCTYPE html>
<html lang="en" >
<head>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css'>
</head>
<body>
<select id="idMulti" class="js-example-basic-multiple" style="width: 100%" multiple="multiple">
<option value="Option 1">Option 1</option>
<option value="Option 2">Option 2</option>
</select>
</body>
<script src='https://code.jquery.com/jquery-3.5.1.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.js'></script>
<script>
$(function() {
$('#idMulti').select2({
placeholder: '',
minimumResultsForSearch: -1,
templateSelection: function (data) {
if (!data.id) { return data.text; }
var selected = ($('#idMulti').val() || []).length;
var total = $('option', $('#idMulti')).length;
return "Selected " + selected + " of " + total;
}
});
});
</script>
</html>
我改了代码
return "Selected " + selected + " of " + total;
到
if(selected==2){
return "Selected " + selected + " of " + total;
}else{
return ""; //here you can return any other message
}
这给出了结果:
【问题讨论】:
-
请添加您面临的问题。什么不起作用?你被困在哪里了?
-
您好,请问是什么问题比较清楚了吗?