Select2 jquery plugin show number of selected items in the result instead of tags

前端 未结 2 989
猫巷女王i
猫巷女王i 2021-01-01 17:35

I am using Select2 jQuery Plugin.

https://select2.github.io/ for reference

When I am using the multiple dropdown option. The result of selec

相关标签:
2条回答
  • 2021-01-01 17:52

    Selectors can certainly be improved, but as a blueprint, adding a counter element on change and hiding the tags like this seems to work as asked.

    $('select').select2({closeOnSelect: false}).on("change", function(e) {
      $('.select2-selection__rendered li:not(.select2-search--inline)').hide();
      $('.counter').remove();
      var counter = $(".select2-selection__choice").length;
      $('.select2-selection__rendered').after('<div style="line-height: 28px; padding: 5px;" class="counter">'+counter+' selected</div>');
    });
    .counter{
      position:absolute;
      top:0px;
      right:5px;
     }
     .select2-search--inline{
       background-color:Gainsboro;
     }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
    <select multiple style="width:100%" id="mySelect">
      <option value="1">Name1</option>
      <option value="2">Name2</option>
      <option value="3">Name3</option>
      <option value="4">Name4</option>
      <option value="5">Name5</option>
      <option value="6">Name6</option>
      <option value="7">Name7</option>
    </select>

    0 讨论(0)
  • 2021-01-01 17:58

    You can add this code after initializing select2

    $('select').on('select2:close', function (evt) {
            var uldiv = $(this).siblings('span.select2').find('ul')
            var count = $(this).select2('data').length
            if(count==0){
              uldiv.html("")
            }
            else{
              uldiv.html("<li>"+count+" items selected</li>")
            }
    

    Ref: jsfiddle
    Reference to select2 events: Here

    Edit:
    If you want to display a blank when user deselects everything, Use this fiddle: here

    Edit:
    Updated to remove flaw in deselection of data and changed it to main answer. Fiddle: here

    0 讨论(0)
提交回复
热议问题