jQuery Chosen Plugin
Without a doubt, my least favorite form element is the SELECT
element. The element is almost unstylable, looks different across platforms, has had inconsistent value access, and disaster that is the result of multiple=true
is, well, a disaster. Needless to say, whenever a developer goes the extra mile to offer solution to these issues, a big smile gets painted on my face. Harvest recently released Chosen, a SELECT
enhancer which offers autosuggest, search, stylability, and an elegant solution for multiple selection. Better yet, Chosen is available for both jQuery and Prototype. Let's take a look at how to use Chosen!
The HTML
Chosen uses true SELECT
elements as the base for its construction, so create your SELECT
and OPTION
elements as usual:
<!-- single dropdown --> <select class="chosen" style="width:200px;"> <option>Choose...</option> <option>jQuery</option> <option selected="selected">MooTools</option> <option>Prototype</option> <option>Dojo Toolkit</option> </select> <!-- multiple dropdown --> <select class="chosen" multiple="true" style="width:400px;"> <option>Choose...</option> <option>jQuery</option> <option selected="selected">MooTools</option> <option>Prototype</option> <option selected="selected">Dojo Toolkit</option> </select>
As expected, Chosen respects the selected
attribute and selects the desired values during construction.
The jQuery JavaScript
The jQuery usage is as you would expect:
jQuery(document).ready(function(){ jQuery(".chosen").chosen(); });
The plugin detects the multiple designation and creates a Facebook-style display, otherwise creates a standard-looking SELECT
element with search capabilities. Chosen also responds to keyboard commands for selection. Brilliant! To change the placeholder text of the given multiple SELECT
, update the placeholder data for the given node:
jQuery(document).ready(function(){ jQuery(".chosen").data("placeholder","Select Frameworks...").chosen(); });
I recommend updating the placeholder as the default "Select Some Options" isn't the most pleasing of messages.
Chosen isn't quite perfect; I'd like to see a maxSelectedOptions option, and possibly an "error" or "required" CSS state. Outside of those small criticisms, I think Chosen is a solid piece of work. Being offered in both jQuery and Prototype is a bonus for users of both JavaScript frameworks. If you hate SELECT
elements as much as I do, give Chosen a try!
Jules Janssen and I did a port to MooTools, https://github.com/julesjanssen/chosen
Any danger of a MooTools port? :) I totally agree – solid replacements are great!
Apologies for broken code there – did not think! To clarify:
Any danger of a MooTools port? I totally agree – solid select element replacements are awesome and really appreciated!
Jules Janssen and I did a port to MooTools, check it out: https://github.com/julesjanssen/chosen