advanced forms

Tailwind CSS Combo Box

The ComboBox JavaScript plugin improves user experience by dynamically suggesting options as users type into an input field.

Class Name
Type
Description
dropdown-itemModifierStyles applied to individual dropdown items.
combo-box-active:{tw-utility-class}ModifierModifies tailwind classes when the combo box is active.
combo-box-selected:{tw-utility-class}ModifierModifies tailwind classes when the combo box is selected.
combo-box-tab-active:{tw-utility-class}ModifierModifies tailwind classes when the combo box tab is active.
combo-box-has-value::{tw-utility-class}ModifierA modifier that enables you to apply Tailwind classes when the SearchBox’s input field contains a value.

The code snippet outlines a ComboBox with specific data attributes to manage its behavior. The outer <div> with data-combo-box signifies that this section is the main ComboBox component. Within it, an <input> field with data-combo-box-input allows users to type text to get suggestions.

An accompanying icon element with data-combo-box-toggle acts as a button to open or close the dropdown menu, indicating it has a dropdown function. The dropdown menu itself is an <div> with data-combo-box-output, which contains several suggestion items. These individual suggestion items are <div> elements with data-combo-box-output-item. Each item has a data-combo-box-search-text attribute that holds the text displayed for that option in the dropdown.

Below example shows basic use of combo-box.

A JSON-based ComboBox example.

A ComboBox, a dropdown component allowing users to type for suggestions, is being set up. The root div includes an attribute apiUrl, indicating the ComboBox where to retrieve data.

In this instance, it’s set to "https://freetestapi.com/api/v1/countries", used to obtain a list of countries.

Another attribute, outputItemTemplate, defines the layout for each item within the dropdown menu. It comprises HTML structure incorporating data-combo-box-output-item to represent individual dropdown items. Each item includes a section for the name (utilizing data-combo-box-output-item-field="name") and a span for a checkmark icon, visible upon item selection.

:apiSearchQuery serves as a property or parameter containing the key name utilized for searching within a dataset when making API calls. Usually, it’s combined with user-entered text to generate a query string, which is then appended to the base API endpoint (apiUrl), resulting in the complete URL required to fetch the data.

:apiQuery represents additional query parameters for the API request, such as limit. :outputEmptyTemplate enables you to specify the content to display when no matching options are available.

The following example demonstrates the usage of search and limit parameters in a combo box.

When isOpenOnFocus is enabled, the dropdown menu will automatically appear upon focusing on the input field.

Alternatively, users have the option to utilize the data-combo-box-toggle attribute, designating an element within the ComboBox responsible for toggling the visibility of the dropdown list.

A basic usage of ComboBox with close button.

Combo box html example with dropdown and modal.

Below is an example showcasing the utilization of the SearchBox within a dropdown, employing data attributes in HTML. Furthermore, the example illustrates how to create groups.

A combo box displaying HTML content within a modal.

Combo box example using JSON data displayed within a dropdown and a modal.

Utilizing a JSON example in a dropdown, use option :apiGroupField to select a heading. Positions are categorized as headings in this scenario.

Combo box with json data show in modal.

Combo box example demonstrating tab filtering functionality, incorporating both dropdown and modal components.

Experience tab filtering within a dropdown. Set :groupingType to tabs, utilize :groupingTitleTemplate to style the filtering tabs, and :tabsWrapperTemplate to style the tab wrapper.

In this example, a modal popup is employed to provide a user-friendly tab filtering experience.

COMMAND
DESCRIPTION
EnterActivates the selected tab.
A-Z a-z
Focuses first item that matches keyboard input.
Home End
Focuses first/last non-disabled item.
EscCloses any open Menus.
Focuses previous/next non-disabled item.
PARAMETERS
DESCRIPTION
OPTIONS
DEFAULT VALUE
General Options
data-combo-boxActivates a ComboBox on a specific element.
:gapDefines the gap between the input field and the dropdown list.number6
:viewportSpecifies the parent element for calculating dropdown list position, by default relative to the document.string, HTMLElement
:preventVisibilityIf true, prevents visibility changes in the ComboBox.booleanfalse
:preventSelectionIf true, prevents item selection in the dropdown list.booleanfalse
:isOpenOnFocusIf true, the dropdown list opens when the field is focused.booleanfalse
:groupingTypeType of grouping used in the dropdown.default, tags
:groupingTitleTemplateTemplate for the title in grouped ComboBox.One line HTML markup
:preventAutoPositionIf true, it disables dropdown auto-positioning.booleanfalse
:tabsWrapperTemplateTemplate for the tabs wrapper in the ComboBox.One line HTML markup<div class="overflow-x-auto p-4"></div>
API Options
:apiUrlThe URL endpoint for fetching data via API.string, null
:apiDataPartSpecifies the part of the returned data to use as the primary data array.string, null
:apiQueryParameters for API requests, like limiting results.string, null
:apiSearchQueryParameter name used for search queries.string, null
:apiHeadersHeaders to include in API requests.object{}
:apiGroupFieldField in the API response used for data grouping.string, null
Template Options
:outputItemTemplateTemplate for individual items in the dropdown list.string, null<div class="dropdown-item combo-box-selected:active" data-combo-box-output-item> ... </div>
:outputEmptyTemplateTemplate for when no data is found in the dropdown.string, nullNothing found...
:outputLoaderTemplateTemplate for the loader when fetching data.string, null<span class="loading loading-spinner text-primary"></span>
:searchWrapperTemplateTemplate for the search field wrapper.string, null<div></div>
Input & Output Options
data-combo-box-inputIdentifies the element responsible for data entry in the ComboBox.
data-combo-box-outputIdentifies the element that outputs data from the ComboBox.
data-combo-box-toggleElement that toggles the dropdown list.
data-combo-box-openElement that open the dropdown list.
data-combo-box-closeElement that close the dropdown list.
data-combo-box-output-itemDefines an element within the initialized container that will handle the display of each individual data item.
> data-combo-box-search-textDefines the element within which text will be searched.
> data-combo-box-valueDefines an element whose text will be set as a value when selected.
> data-combo-box-output-item-fieldDefines a data field that will be taken to fill the element with text.
> data-combo-box-output-item-attrDefines the attributes that will be filled with the corresponding data. For example, the src attribute of an image.
:valueFromField name from which data will be taken.string
:attrAttribute name where data will be supplied.string

The HSCombobox object is contained within the global window object.

METHOD
DESCRIPTION
PUBLIC METHODS
open()Opens the autosuggestion list.
close()Closes the autosuggestion list.
recalculateDirection()Forces recalculation of the autosuggestion list’s positions.
STATIC METHODS
HSCombobox.getInstance(target, isInstance)
Returns the element associated with the target.
  • The target can be a Node or a valid CSS selector.
  • isInstance (boolean) - returns the instance instead of the Node if true.
HSCombobox.autoInit()Reinitializes all ComboBoxes on the page.
HSCombobox.close(target)
Closes the target ComboBox.
  • The target should be a Node or a valid CSS selector.
HSCombobox.closeCurrentlyOpened()Closes the currently opened ComboBox.

Below, is the demonstration on how to use the methods. To test other methods, copy the following methods into your console and click the button.

Open item (public method).

// This method is used in above example.
const comboBox = HSComboBox.getInstance(document.querySelector('#combo-box-method'), true).element
const openBtn = document.querySelector('#open-btn')

openBtn.addEventListener('click', () => {
comboBox.open()
})

Open item (mixed).

const { element } = HSComboBox.getInstance('#combo-box-method', true);
const openBtn = document.querySelector('#open-btn');

openBtn.addEventListener('click', () => {
element.open();
});