Select2 jQuery Plugin: How to Display Number of Selected Items Instead of Tags in Multiple Dropdown
Select2 is a popular jQuery plugin that enhances the functionality and appearance of HTML dropdowns (<select> elements). It adds features like searchability, tagging, remote data loading, and custom styling, making it a go-to choice for developers looking to improve user experience with dropdowns.
One common use case for Select2 is multiple selection, where users can choose more than one option from a list. By default, Select2 displays selected items as "tags" (small, inline boxes) within the dropdown’s selection area. While this works well for a few selections, it quickly becomes problematic when users select many items: tags overflow, clutter the UI, and may even break the layout on smaller screens (e.g., mobile devices).
In this blog, we’ll explore how to customize Select2 to display the number of selected items (e.g., "3 items selected") instead of individual tags when multiple options are chosen. This approach keeps the UI clean, scalable, and user-friendly—even for large numbers of selections.
Table of Contents#
- Prerequisites
- Setting Up Select2
- Default Multiple Selection Behavior
- Customizing to Display Selected Item Count
- Step-by-Step Implementation
- Advanced Customizations
- Troubleshooting Common Issues
- Conclusion
- References
Prerequisites#
Before diving in, ensure you have the following:
- Basic Knowledge: Familiarity with HTML, CSS, JavaScript, and jQuery.
- Dependencies:
- jQuery (required for Select2 to work).
- Select2 plugin (CSS and JavaScript files).
You can include these dependencies via CDN or download them locally:
- jQuery: jquery.com (v3.x recommended).
- Select2: select2.org (v4.x recommended).
Setting Up Select2#
First, let’s set up a basic Select2 multiple dropdown to understand the default behavior.
Step 1: Basic HTML Markup#
Start with a standard <select> element with the multiple attribute to enable multiple selections:
<!-- HTML -->
<select id="mySelect2" class="form-control" multiple>
<option value="1">Apple</option>
<option value="2">Banana</option>
<option value="3">Cherry</option>
<option value="4">Date</option>
<option value="5">Elderberry</option>
<option value="6">Fig</option>
</select> Step 2: Include Dependencies#
To use Select2, you need to include jQuery and Select2’s CSS/JavaScript files. Use CDNs for simplicity:
<!-- jQuery (required for Select2) -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- Select2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<!-- Select2 JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script> Step 3: Initialize Select2#
Initialize Select2 on the <select> element using jQuery:
// JavaScript
$(document).ready(function() {
$('#mySelect2').select2({
placeholder: "Select fruits (hold Ctrl/Cmd to select multiple)", // Placeholder text
allowClear: true // Optional: Add a "clear all" button
});
}); Default Multiple Selection Behavior#
By default, when you enable multiple selection in Select2, each selected item is displayed as a "tag" (a small, removable box) within the dropdown’s selection area. For example:
- Selecting "Apple" and "Banana" shows two tags:
[Apple] [Banana]. - Selecting 5+ items results in a cluttered UI, with tags overflowing horizontally or wrapping onto new lines.
This is problematic for:
- Small screens: Tags may overflow the container, breaking the layout.
- Many selections: Users can’t quickly see how many items they’ve chosen without counting tags.
- Clean design: Tags can distract from the overall UI aesthetic.
Customizing to Display Selected Item Count#
To solve this, we’ll override Select2’s default selection display using the templateSelection option. This option lets you define a custom function to control how selected items are rendered in the dropdown’s selection area.
How templateSelection Works#
The templateSelection function takes a data parameter representing the currently rendered option (a single data object), and returns a string or jQuery object representing the HTML to display. Since it only receives one item at a time, we need to query Select2's data to get the total count of selected items.
Our goal is to:
- Show the placeholder if no items are selected.
- Show the selected item’s text if only one item is selected.
- Show
"{n} items selected"(e.g., "3 items selected") if multiple items are selected.
Step-by-Step Implementation#
Let’s walk through the process of modifying the Select2 initialization to display the count of selected items instead of tags.
Step 1: Update the Select2 Initialization#
Modify the Select2 initialization code to include the templateSelection function:
$(document).ready(function() {
$('#mySelect2').select2({
placeholder: "Select fruits (hold Ctrl/Cmd to select multiple)",
allowClear: true,
templateSelection: function(data) {
// Get the count of all selected items
const selectedCount = $('#mySelect2').select2('data').length;
if (selectedCount === 0) {
return "Select fruits..."; // Fallback if placeholder isn't working
}
// If 1 item is selected, show its text
if (selectedCount === 1) {
return data.text;
}
// If multiple items are selected, show the count
return `${selectedCount} items selected`;
}
});
}); Step 2: Test the Behavior#
After adding templateSelection, test the dropdown:
- No selections: Shows the placeholder ("Select fruits...").
- 1 selection: Shows the selected item’s text (e.g., "Apple").
- 2+ selections: Shows "2 items selected", "3 items selected", etc.
Step 3: Style the Count Display (Optional)#
To make the count stand out, add custom CSS to style the selection area. For example:
/* Style the selected count container */
.select2-selection__rendered {
padding: 6px 12px !important; /* Add padding */
background-color: #f8f9fa; /* Light gray background */
border-radius: 4px; /* Rounded corners */
font-weight: 500; /* Slightly bold text */
}
/* Optional: Style the "clear all" button */
.select2-selection__clear {
margin-right: 10px !important;
} Advanced Customizations#
1. Show a Tooltip with All Selected Items#
Users may want to see the full list of selected items without opening the dropdown. Add a tooltip using the title attribute:
templateSelection: function(data) {
const selectedCount = $('#mySelect2').select2('data').length;
if (selectedCount === 0) {
return "Select fruits...";
}
// Get a comma-separated list of selected item texts
const allSelectedTexts = $('#mySelect2').select2('data').map(item => item.text).join(", ");
if (selectedCount === 1) {
return $(`<span title="${allSelectedTexts}">${data.text}</span>`);
}
// Show count with tooltip listing all items
return $(`<span title="${allSelectedTexts}">${selectedCount} items selected</span>`);
} Now, hovering over the count displays a tooltip with all selected items (e.g., "Apple, Banana, Cherry").
2. Highlight the Count for Large Selections#
Change the count's color if the number of selected items exceeds a threshold (e.g., 5 items):
templateSelection: function(data) {
const selectedCount = $('#mySelect2').select2('data').length;
if (selectedCount === 0) {
return "Select fruits...";
}
const allSelectedTexts = $('#mySelect2').select2('data').map(item => item.text).join(", ");
let countHtml;
if (selectedCount === 1) {
countHtml = `<span title="${allSelectedTexts}">${data.text}</span>`;
} else {
// Add red color if >5 items are selected
const color = selectedCount > 5 ? "color: #dc3545;" : "";
countHtml = `<span title="${allSelectedTexts}" style="${color}">${selectedCount} items selected</span>`;
}
return $(countHtml);
} 3. Click the Count to Clear Selections#
Add a click handler to the count to clear all selections (requires allowClear: true):
templateSelection: function(data) {
const selectedCount = $('#mySelect2').select2('data').length;
if (selectedCount === 0) {
return "Select fruits...";
}
const allSelectedTexts = $('#mySelect2').select2('data').map(item => item.text).join(", ");
const $count = $(`<span title="${allSelectedTexts}">${selectedCount} items selected</span>`);
// Clear selections when the count is clicked
$count.on("click", function() {
$('#mySelect2').val(null).trigger("change");
});
return $count;
} Troubleshooting Common Issues#
1. "Select2 is not defined" Error#
Cause: Select2 depends on jQuery, and if jQuery is loaded after Select2, the plugin won’t initialize.
Fix: Load jQuery first, then Select2.
2. Placeholder Not Showing When No Selections#
Cause: The placeholder option may be missing or overridden.
Fix: Ensure placeholder is set in Select2 initialization, and return the placeholder text in templateSelection when no items are selected (check via $('#mySelect2').select2('data').length === 0).
3. Count Not Updating After Deselection#
Cause: Select2 automatically re-runs templateSelection on selection/deselection, so this is rare.
Fix: Use $('#mySelect2').select2('data').length to get the current selection count.
4. Tooltip Not Working#
Cause: Browsers may block tooltips on custom elements.
Fix: Use a library like Tooltipster for more reliable tooltips, or ensure the title attribute is added to a standard HTML element (e.g., <span>).
Conclusion#
By customizing Select2’s templateSelection option, you can replace cluttered tags with a clean "X items selected" display for multiple dropdowns. This improves readability, reduces UI clutter, and enhances user experience—especially for mobile users or when many items are selected.
With advanced customizations like tooltips, conditional styling, and click-to-clear, you can tailor the behavior to fit your application’s needs.