@noli42/chosen
v3.1.3
Published
Chosen is a library for making long, unwieldy select boxes more friendly.
Readme
Chosen
Chosen is a lightweight JavaScript library for making long, unwieldy select boxes more user-friendly.
It enhances standard HTML <select> elements with a searchable, more usable interface while keeping the original form element intact.
Chosen has no jQuery dependency and does not require any other external JavaScript libraries. It is written in plain JavaScript and can be used directly in modern web projects.
For downloads, see: https://github.com/noli42/chosen/releases
Demo
A live demo is available on GitHub Pages:
Usage
Include the JavaScript and CSS files, then call chosen() on a select element.
<link rel="stylesheet" href="chosen.css">
<script src="chosen.js"></script>
<select id="country-select">
<option value=""></option>
<option value="hu">Hungary</option>
<option value="de">Germany</option>
<option value="fr">France</option>
</select>
<script>
document.getElementById("country-select").chosen({
search_contains: true
});
</script>Usage with npm
npm install @noli42/chosenImport the JavaScript, then import the CSS:
import "@noli42/chosen";
import "@noli42/chosen/chosen.css";
const select = document.querySelector("#country-select");
window.Chosen.init(select, {
search_contains: true
});The original DOM API is also available:
select.chosen({
search_contains: true
});Usage with React
Chosen is a DOM-based select enhancement library, so initialize it after the <select> element has mounted. In React, that usually means calling it inside useEffect.
import { useEffect, useRef } from "react";
import "@noli42/chosen";
import "@noli42/chosen/chosen.css";
export function ChosenSelect() {
const selectRef = useRef(null);
useEffect(() => {
const select = selectRef.current;
if (!select || !window.Chosen) {
return;
}
window.Chosen.init(select, {
search_contains: true
});
return () => {
window.Chosen.destroy(select);
};
}, []);
return (
<select ref={selectRef}>
<option value=""></option>
<option value="hu">Hungary</option>
<option value="de">Germany</option>
<option value="fr">France</option>
</select>
);
}For dynamic options, notify Chosen after React updates the <option> elements:
useEffect(() => {
if (!selectRef.current) {
return;
}
selectRef.current.dispatchEvent(new Event("chosen:updated"));
}, [options]);Chosen can be imported in server-rendered applications, but initialization still requires a browser DOM. Call window.Chosen.init(...) only on the client, for example inside useEffect.
Chosen Credits
- Concept and development by Patrick Filler for Harvest
- Design and CSS by Matthew Lettini
- 1.8.x and earlier maintained by @pfiller, @kenearley, @stof, @koenpunt, and @tjschuck
- 2.0.x and later maintained by @JJJ and contributors
- 3.0.x and later maintained by @noli42 and contributors
- Chosen includes contributions by many fine folks
