advanced forms

Tailwind CSS Advanced select

The Advanced Select Component enhances traditional select boxes with features like search and tagging, offering versatility for complex selection needs.

Class Name
Type
Description
advance-select-toggleComponentThe advance-select-toggle component class is used for :toggleClasses, providing base styles to select toggle.
advance-select-menuComponentThe advance-select-menu component class is used for :dropdownClasses, providing base styles to select dropdown menu.
advance-select-optionComponentThe advance-select-option component class is used for :optionClasses, providing base styles for individual select dropdown options.
.advance-select-tagComponentThe .advance-select-tag component class is utilized for wrapperClasses when :mode is configured as tag.
select-opened:{tw-utility-class}ModifierThe modifier allows setting Tailwind classes when a select has been opened.
select-disabled:{tw-utility-class}ModifierThe modifier allows setting Tailwind classes when a select has the disabled attribute.
selected:ModifierThe modifier allows setting Tailwind classes when a option is selected.
advance-select-xsResponsiveApply advance-select-xs along with advance-select-toggle to implement a extra small size.
advance-select-smResponsiveApply advance-select-sm along with advance-select-toggle to implement a small size.
advance-select-lgResponsiveApply advance-select-lg along with advance-select-toggle to implement a large size.

A basic usage of advanced select.

Please refer to the Basic option section for all basic functionalities.

To customize the placeholder with either an icon or plain text, you can provide custom HTML within the "placeholder:" option as demonstrated below.

Choose between different sizes of advanced selects by using advance-select-xs for extra small size ,advance-select-sm for small size and advance-select-lg for large size within the "toggleClasses": section. You can also create a custom size using Tailwind’s padding utility p-*.

Success state can be show using is-valid class.

Error state can be show using is-invalid class.

To fix the dropdown’s vertical placement, you can specify the dropdownVerticalFixedPlacement: option and define the desired position, as demonstrated in the example below.

To render selects as inactive, include the disabled boolean attribute within the select element and utilize the class select-disabled:* within the "toggleClasses": section for styling purposes. If you’re employing advance-select-toggle, disabled state styling has been incorporated.

Select multiple options.

Please refer to the Multiple option section for all multiple related functionalities.

Select multiple options and add an option template.

If you only want to display the number of the selected option in multiple select. then use "toggleCountText":.

Use multiple tag to enable counter option that counts the number of selected options.

To enable searching within the dropdown, set "hasSearch": true.

Please refer to the Search option section for all search-related functionalities.

Set a maximum limit for search results by using the parameter searchLimit: 5.

Set isSearchDirectMatch: false to turn off direct match searching, allowing for broader search results without exact term matching.

Create a custom select with removable tags using the provided options:

  • "wrapperClasses": This option wraps the select element. Apply the class advance-select-tag for default styling.
  • "tagsItemTemplate": This section is dedicated to styling the selected tag.
  • Use data-select-option to customize options.

Please see the Tags option section for tag-related functionalities.

Example of custom option with avatar and icons. Using data-select-option for providing content for the option.

Basic example of options with icon.

Basic example of options with avatar.

Basic usage in modal window.

Utilize the addOption and removeOption methods to add or remove options, respectively.

The destroy method is provided to facilitate the destruction of a select element.

Provides setValue method that helps to set a value programmatically.

Provides setValue method that helps to set a value programmatically.

Set apiUrl: "https://some-path.com/api" to configure selection based on remote data, allowing data to be fetched dynamically from the specified API endpoint.

Allow multiple options to be selected by setting apiUrl: "https://some-path.com/api", enabling dynamic selection from remote data provided by the specified API endpoint.

Enable selection with removable tags using apiUrl: "https://some-path.com/api", allowing choices to be dynamically loaded from remote data and displayed as tags.

Enable multiple option selection with a custom template by setting apiUrl: "https://some-path.com/api". This allows selections to be dynamically built from remote data with a specified option format.

Use multiple tag to enable counter option that counts the number of selected options. Use apiUrl: "https://some-path.com/api" to enable build select according to the remote data.

Create a custom selection design featuring avatars by setting apiUrl: "https://some-path.com/api". This enables options to be dynamically loaded from remote data and displayed with personalized avatar styling..

Use dropdownScope: "window" to display a select dropdown inside a parent element with hidden overflow, ensuring the dropdown remains visible and accessible within the window scope.

When dropdownScope is set to window, the dropdownClasses include w-full (required to update updateDropdownWidth()) and z-[80] (necessary to ensure the dropdown displays above the backdrop).

PARAMETERS
DESCRIPTION
OPTIONS
DEFAULT VALUE
Basic Options
data-selectUsed to create a custom select options.--
data-select-optionUsed to add a custom option with a description and an icon.--
:placeholderDefine a default placeholder when nothing is selected.stringSelect...
:toggleClassesDefine CSS classes for the selects’ toggle (styles the button). CSS classes must be separated by a space.string-
:toggleTagDefine the markup structure for the select toggle.Note: data-title is required if you are using a custom placeholder.One line HTML markup
:dropdownClassesDefine CSS classes for the dropdown menu. CSS classes must be separated by a space.string-
:dropdownPlacementSpecifies the position of the menu when opened.top, top-start, top-end, bottom, bottom-start, bottom-end, right, right-start, right-end, left, left-start, left-endbottom
:dropdownVerticalFixedPlacementSpecifies a fixed vertical position for the menu when opened. It will not change when scrolling."top" / "bottom" / nullnull
:dropdownScopeDetermines whether the dropdown will be moved outside the parent, for correct display in elements with hidden overflow. Requires the Popper plugin.window, parentparent
:optionClassesStyling is applied to individual options, so use Tailwind CSS classes to style the options.string-
:optionTemplateDefine template for the single option. It could contain:
  • data-icon attribute: If the target option tag contains data-select-option:icon, the specified image will be placed within the tag with this attribute.
  • data-title attribute: The text from the target option will be inserted inside the tag with this attribute.
  • data-description attribute: If the target option tag contains data-select-option:description, the specified text will be placed inside the tag with this attribute.
One line HTML markup-
:extraMarkupProvide markup that can be added to the select wrapper for decorative purposes.One line HTML markup or Array of one line HTML markup-
:isOpenedIf the value is true, the select is opened.booleanfalse
:dropdownSpaceYou have the ability to adjust the spacing between the select element and its menu.number10
:optionTagDefine the markup for the wrapper tag of a single option.
Do not update. This HTML markup must remain as is. Changing it could potentially cause issues.
One line HTML markup<div></div>
:descriptionClassesSpecify CSS classes for the description within each individual option. Ensure that the classes are separated by a space.string-
:iconClassesSpecify CSS classes for the icons within each individual option. Ensure that the classes are separated by a space.string-
Multiple Options
:toggleCountTextThis feature is exclusive to multiple select. It defines the text to appear after the counter and activates the counting mode.string-
:toggleCountTextPlacementAllows to specify where the text specified in the toggleCountText parameter will be located relative to the counter.'postfix' / 'prefix' / 'postfix-no-space' / 'prefix-no-space'postfix
:toggleCountTextMinItemsThis feature is specific to multiple selects. It sets the minimum number of selected items required to activate the counting mode.number1
:toggleSeparatorsDefine separators for the toggle options in the selects.object-
:toggleSeparators:itemsDefine which separator will be used for separate selected items.string`,
:toggleSeparators:betweenItemsAndCounterDefine which separator will be used for separate selected items and counter text.stringand
:toggleCountTextModeThis option is only available for multiple select. controls the display of the contents of the button title.‘countAfterLimit’ or ’nItemsAndCount’countAfterLimit
Search Options
:hasSearchIf the value is true, include a search field within the dropdown.booleanfalse
:preventSearchFocusIf the value is true, disable autofocus for the search field within the dropdown list.booleanfalse
:searchWrapperTemplateDefine the markup for the wrapper tag for the search.
Do not update. This HTML markup must remain as is. Changing it could potentially cause issues.
One line HTML markup<div></div>
:searchWrapperClassesProvide the option to style the search wrapper using Tailwind classes. Make sure the classes are separated by spaces.stringbg-base-100 sticky top-0 mb-2 px-2 pt-3
:searchIdThis option is only available when hasSearch: true. This option is useful if there is a need to associate a label outside the initialized element with the search input.string-
:searchClassesApply Tailwind CSS classes to style the search bar. Ensure that the classes are separated by a space.stringborder-base-content/40 focus:border-primary focus:ring-primary bg-base-100 block w-full rounded-btn border px-3 py-2 text-base focus:ring-1
:searchPlaceholderThis option is applicable only when the :hasSearch attribute is set to true. It specifies the placeholder text for the search field within the dropdown.stringSearch...
:searchNoResultTextSpecifies the text to be shown when no results are found.stringNo options found...
:searchNoResultClassesSpecify CSS classes for the wrapper surrounding the “no results” message. Ensure that the classes are separated by a space.stringblock advance-select-option

advance-select-option class is a custom class. Refer to the class table for more details.
:optionAllowEmptyOptionThis option allows the inclusion of an empty option in the list. When enabled (true), an additional option with an empty string ("") as its value will be displayed, providing users the ability to select a blank choice if necessary.booleanfalse
:searchLimitThis option is only available when hasSearch: true. If this option is enabled, the search will display only the first ’n’ matching items.numberinfinity
:isSearchDirectMatchThis option is only available when hasSearch: true. If the option is disabled, then in the search results you will be able to see non-direct matches by text. For example, if you entered england in the search field, then Eng-land, Eng.land, Eng_land will also be shown.booleantrue
:searchNoResultTemplateThis option is only available when :hasSearch attribute is true. Define a markup for the “no result” text.string<span></span>
Tags Options
:modeDefine a select mode.default or tagsdefault
:dropdownTagSpecify the markup for the dropdown accordingly.
Do not update. This HTML markup must remain as is. Changing it could potentially cause issues.
One line HTML markup<div></div>
:wrapperClassesDefine CSS classes for the wrapper of the select elements. These classes are applied to the main wrapper. Ensure that the classes are separated by spaces.string-
:tagsItemTemplateDefine template for the single option. It could contain:
  • data-icon attribute: If the target option tag contains data-select-option:icon, the specified image will be placed within the tag with this attribute.
  • data-title attribute: The text from the target option will be inserted inside the tag with this attribute.
  • data-description attribute: If the target option tag contains data-select-option:description, the specified text will be placed inside the tag with this attribute.
One line HTML markup-
:tagsItemClassesApply styling to the select tag wrapper. Ensure that the classes are separated by spaces.string-
:tagsInputIdThis option is only available when tags mode is set up. This option is useful if there is a need to associate a label outside the initialized element with the tags input.string-
:tagsInputClassesThis work as input for search. Specify CSS classes for the input field within the dropdown list. Ensure that the classes are separated by spaces.string-
:isAddTagOnEnterWhen you search and press Enter, it creates an entry within the options. This setting determines whether a tag will be added when the Enter key is pressed.booleantrue
Remote Data Options
:apiUrlDefines the address where the API is located.string, nullnull
:apiQueryDefines query parameters that are separated by ?.string, nullnull
:apiOptionsDefines options for the fetch function.RequestInit , nullnull
:apiDataPartIf data is in some first level parameter, then it allows you to specify the name of this parameter to extract the data.string , nullnull
:apiSearchQueryKeyDefines the key for the query search parameter.string , nullnull
:apiFieldsMapAllows you to convert fields from the API to the fields required for the plugin to work.{ id: string; title: string; icon?: string, null; description?: string, null} , nullnull
:apiIconTagAllows to define an img tag that will be used when rendering options and in the trigger button.string , nullnull

The HSSelect object is contained within the global window object.

METHOD
DESCRIPTION
PUBLIC METHODS
destroy()Destroys select.
open()Open dropdown list.
close()Close dropdown list.
setValue()Set the select value: use a string for a single select and an array for a multiple select.
addOption(items)Include an option, or potentially multiple options, to the select menu. Each individual option should adhere to this interface.
{ title: string; val: string; options?: { description: string; icon: string; }; }
removeOption(val)Remove an option by its value (multiple options possible).
recalculateDirection()Trigger a recalculation for the dropdown list.
STATIC METHODS
HSSelect.getInstance(target, isInstance)
Returns the element linked to the target.
  • target should be a Node or string (valid selector).
  • isInstance boolean. Returns the instance instead of Node if true.
HSSelect.close(target).
Close the element linked to the target.
  • target should be a Node or string (valid selector).
HSSelect.closeCurrentlyOpened(evtTarget)
Close the element linked to the target.
  • target should be a Node.

Below is a demonstration of how to use the methods. Assign an ID to the data-select element. To test other methods, copy the following code into your console and click the button.

Open item (public method).

<select id="select" class="--prevent-on-load-init" data-select>
...
</select>

// This method is used in above example.
const select = new HSSelect(document.querySelector('#method-select'));
const openBtn = document.querySelector('#open-btn');

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

Open item (static method).

const openBtn = document.querySelector('#open-btn');

openBtn.addEventListener('click', () => {
  HSSelect.open('#select');
});

Open item (mixed).

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

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

Set value.

const select = HSSelect.getInstance('#select');
const setValueBtn = document.querySelector('#set-value-btn');

setValueBtn.addEventListener('click', () => {
  select.setValue('address');
  // if select is multiple
  // select.setValue(['address', 'email']);
});

Add options (public method).

const select = window.HSSelect.getInstance('#add-remove-select');
const addOptionsBtn = document.querySelector('#add-option');

addOptionsBtn.addEventListener('click', () => {
  select.addOption([
    {
      title: "James Collins",
      val: "1",
    },
    {
      title: "Amanda Harvey",
      val: "2",
    }
  ]);
});

Remove options (public method).

const select = window.HSSelect.getInstance('#add-remove-select');
const removeOptionsBtn = document.querySelector('#remove-option');
removeOptionsBtn.addEventListener('click', () => {
  select.removeOption(["1", "2"]);
});

Destroy instance (public method).

const destroyBtn = document.querySelector('#destroy-btn');
const select = window.HSSelect.getInstance('#destroy-select');
destroyBtn.addEventListener('click', () => {
  select.destroy();
});
METHOD
DESCRIPTION
RETURNING VALUE
on:changeCalled when any select is changed.Current value

Display a console log message when an option is selected.

When select changes event example.

const el = HSSelect.getInstance(document.getElementById('event-select'));

el.on('change', (instance) => {console.log("selected")});