how to show custom text with badge count of selected items from the select tag list using select2 plugin

12 Views Asked by At

I wants to show a custom text in the search-field of the select2 with count as a number of items selected from the list instead of showing tags in the search field, i tried so many ways but i got the proper solution

Working Solution

HTML Code
<select id="filterTherapy" multiple class="form-select form-select-solid">
  <option value="oncology">Oncology</option>
  <option value="neurology">Neurology</option>
  <option value="radiology">Radiology</option>
  <option value="biology">Biology</option>
  <option value="psychology">Psychology</option>
</select>

JS Code
$('#filterTherapy').select2({
  placeholder: 'Therapy',
  allowClear: true
});

//Update badge count on change
$('#filterTherapy').on('change', function (e) {
const selectedCount = $(this).select2('data').length;
const badgeText = selectedCount \> 0 ? 'Therapy \<span class="badge bg-primary"\>' + selectedCount + '\</span\>' : '';
// Use the specific class for the rendered area of the targeted select
$('#filterTherapy').next('.select2-container').find('.select2-selection__rendered').html(badgeText);
});
0

There are 0 best solutions below