【问题标题】:Select2 templateSelection issueSelect2 模板选择问题
【发布时间】: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
}

这给出了结果:

Result of the code above

【问题讨论】:

  • 请添加您面临的问题。什么不起作用?你被困在哪里了?
  • 您好,请问是什么问题比较清楚了吗?

标签: javascript jquery-select2


【解决方案1】:

只需更改这一行:

return "Selected " + selected + " of " + total;

if(selected==2){
    return "Selected " + selected + " of " + total;
}else{
    return ""; //here you can return any other message
}

如果用户选择 > 2 个选项,如果用户未选择任何选项等,您可以对其进行编辑以添加更多条件

【讨论】:

    猜你喜欢
    • 2021-01-24
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2017-10-07
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多