cmSelect JavaScript API
window.cmSelect initialises a TomSelect dropdown on a <select> element, optionally loading its options from a URL. cm-admin uses it for every select field; call it yourself for selects you render in custom partials or JavaScript.
tip
For form fields declared with form_field, you don't need JavaScript: use options_url. It replaces the old ajax_url option.
Quick exampleβ
window.cmSelect("#my-select", { url: "/admin/users/options" });
Usageβ
Pass a <select> element or a selector β one element at a time:
window.cmSelect(document.querySelector("#my-select"));
window.cmSelect("#my-select");
- The default search query parameter is
search. - To set the value manually, use
element.tomselect.setValue(value).
Optionsβ
| 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 formatβ
The endpoint must return an array of objects with id and title keys:
| Key | Type | Description |
|---|---|---|
id | String/Number | The value stored on selection. |
title | String | The label shown in the dropdown. |
[
{ "id": 1, "title": "User One" },
{ "id": 2, "title": "User Two" },
{ "id": 3, "title": "User Three" }
]
users.map { |user| { id: user.id, title: user.name } }
note
If a TomSelect instance already exists on the element, it is destroyed and re-initialised with the new configuration (see reinitializeSelect).
Recipesβ
Load options from a URLβ
window.cmSelect(element, {
url: "/cm_admin/users/options"
});
Extra query parameters and callbacksβ
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);
}
});