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

I am using Select2 jQuery Plugin.

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

When I am using the multiple dropdown option. The result of selected items is shown as tags in a box but, I just want to show the number of items selected.

Is it possible with Select2 jQuery plugin

HTML

<select multiple style="width:100%">
  <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>

JS

$('select').select2();

I want output as below

enter image description here

instead of tag like output.

Example working Fiddle

Answers:

Answer

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

Answer

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>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.