Skip to main content

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​

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 format​

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

KeyTypeDescription
idString/NumberThe value stored on selection.
titleStringThe 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);
}
});