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â
- Pass element to
window.cmSelect, likewindow.cmSelect(document.querySelector("#my-select"), ...); - Pass a selector to
window.cmSelect, likewindow.cmSelect("#my-select", ...); - It works on a single select element at a time.
- Default search parameters is
search - 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â
| Option | Type | Description |
|---|---|---|
url | String | The endpoint URL to fetch options from. When provided, enables Fetch mode. |
queryData | Object | Additional query parameters to append to the URL. |
onSuccess | Function | Callback function called with the response data on successful fetch. |
onError | Function | Callback function called with the error on fetch failure. |
reinitializeSelect | Boolean | Default: 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:
| Key | Type | Description |
|---|---|---|
id | String/Number | The value to be stored on selection. |
title | String | The 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.