Skip to main content

cmSelect Integration 🎯

This module provides a wrapper around TomSelect for creating dynamic select dropdowns with Fetch support.

Important

With cmSelect, ajax_url is changed to options_url

Overview​

window.cmSelect is a global function that initializes TomSelect on a given element with optional fetch configuration for fetching options dynamically.

Basic Usage​

Manual Initialization​

  1. Pass element to window.cmSelect, like window.cmSelect(document.querySelector("#my-select"), ...);
  2. Pass a selector to window.cmSelect, like window.cmSelect("#my-select", ...);
  3. It works on a single select element at a time.
  4. Default search parameters is search
  5. To set the value of the select manually from JavaScript, use element.tomselect.setValue(value)
window.cmSelect(document.querySelector("#my-select"));
window.cmSelect("#my-select");

Fetch Configuration​

Basic Fetch Setup​

window.cmSelect(element, {
url: "/cm_admin/users/options"
});

Full Options​

window.cmSelect(element, {
url: "/cm_admin/users/options",
queryData: {
some_id: 3,
some_val: 5
},
onSuccess: function (data) {
console.log("Data loaded:", data);
},
onError: function (error) {
console.error("Failed to load:", error);
}
});

Options Reference​

OptionTypeDescription
urlStringThe endpoint URL to fetch options from. When provided, enables Fetch mode.
queryDataObjectAdditional query parameters to append to the URL.
onSuccessFunctionCallback function called with the response data on successful fetch.
onErrorFunctionCallback function called with the error on fetch failure.
reinitializeSelectBooleanDefault: true. Whether to reinitialize the TomSelect instance (destroy current and reinitialize).

Response Convention​

The server endpoint must return an array of hashes with id and title keys:

KeyTypeDescription
idString/NumberThe value to be stored on selection.
titleStringThe label displayed in the dropdown.

Example Response:

[
{ "id": 1, "title": "User One" },
{ "id": 2, "title": "User Two" },
{ "id": 3, "title": "User Three" }
]

Ruby Example:

users.map { |user| { id: user.id, title: user.name } }

💡 Note: If a TomSelect instance already exists on the element, it will be destroyed and re-initialized with the new configuration.