Combobox
A pure vanilla JS implementation of Zag JS Combobox
Anatomy
The Combobox component consists of the following data-part
root
label
control
title
input
clear-trigger
trigger
positioner
content
item
If you have a lot of data, you can also load the collection with a json file
You first need to add a inline script including the collection as well as the collection name
<script type="application/json" data-combobox="countries">
[
{ "label": "France", "code": "FR" },
{ "label": "Belgium", "code": "BE" },
{ "label": "Germany", "code": "DE" },
{ "label": "Italy", "code": "IT" },
{ "label": "Spain", "code": "ES" },
{ "label": "Portugal", "code": "PT" },
{ "label": "Netherlands", "code": "NL" },
{ "label": "Switzerland", "code": "CH" },
{ "label": "Austria", "code": "AT" },
{ "label": "Poland", "code": "PL" },
{ "label": "Czech Republic", "code": "CZ" },
{ "label": "Hungary", "code": "HU" },
{ "label": "Greece", "code": "GR" }
]
</script>
Data attributes
Each combobox can be set with different settings with the following data-attribute.
Callbacks
Each combobox component can receive callbacks that can be used to respond to user interaction with custom behavior.
You must add a custom id and an event listener for your event name
document.getElementById("my-callback-combobox")
?.addEventListener("my-callback-combobox-event", (event) => {
console.log("Received event:", (event as CustomEvent).detail);
});
Open your browser's console to see the events received when you open or close the above combobox
Use with Form
Combobox can be used inside a form
You must set the id of the form and the name of the Combobox
data-form="form-id"
data-name="combobox-name"
You can use the results from the form as you wish
const formCurrency = document.getElementById('my-form') as HTMLFormElement | null;
const resultCurrency = document.getElementById('result') as HTMLDivElement | null;
if (formCurrency && resultCurrency) {
formCurrency.addEventListener('submit', (e: Event) => {
e.preventDefault();
const formData = new FormData(formCurrency);
const currency = (formData.get('currency') as string) || 'none';
resultCurrency.textContent = `Submitted currency: ${currency}`;
});
}
Templates
Combobox components is available in the followng templates
-
Corex template
Default corex templates. It provides the global, semantic and components tokens
-
Modex template
Based on Corex default template, it adds dark and light mode option to the tokens
-
Themex template
Based on the Corex default template, it adds theming capabilities as well as light and dark mode options to the tokens.