jQuery Chosen Plugin

By  on  
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!

Recent Features

  • By
    Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today's websites and devices become ever more varied, a plethora of responsive images...

  • By
    CSS Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

Incredible Demos

  • By
    JavaScript Speech Recognition

    Speech recognition software is becoming more and more important; it started (for me) with Siri on iOS, then Amazon's Echo, then my new Apple TV, and so on.  Speech recognition is so useful for not just us tech superstars but for people who either want to work "hands...

  • By
    Optimize Your Links For Print Using CSS — Show The URL

    When moving around from page to page in your trusty browser, you get the benefit of hovering over links and viewing the link's target URL in the status bar. When it comes to page printouts, however, this obviously isn't an option. Most website printouts...

Discussion

  1. Jules Janssen and I did a port to MooTools, https://github.com/julesjanssen/chosen

  2. Marc Fowler

    Any danger of a MooTools port? :) I totally agree – solid replacements are great!

  3. Marc Fowler

    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!

  4. Jonnathan

    Jules Janssen and I did a port to MooTools, check it out: https://github.com/julesjanssen/chosen

    • Dutchie

      Nice, will check it out.
      Saw the jquery one and thought it need a moooo port as well :)

    • psren

      For me it’s a strange behaviour that if i got 4 options (test1,test2,test3,test4) and i type in “test4” and press Enter that it selects “test1”. I’ve to press down key first. Bug or Feature?

  5. Nice. I will try for the mootools now…

  6. Nice! Thanks for sharing.

    @Jonnathan thanks for the Moo port.

  7. Small bug with the plugin, the “Choose…” value is selectable, is there a way to disable it?

    • Set an attribute of disabled with the value disabled, like so:

      Choose...

    • Woops. I guess “wrap your code in doesn't work like it said above the comment box. How's this: http://jsfiddle.net/hzuAt/

  8. shame… maybe it does but I added a closing tag… regardless you get the point.

  9. There are some z-index issues with IE7 when using multiple select boxes on the same page, one underneath the other. A fix can be found here for those having the same problem:
    https://github.com/harvesthq/chosen/issues/74#issuecomment-1721164

  10. great plugin, any chance you add it to nuget.org

    • Unfortunately no because NuGet is a framework that wouldn’t be compatible with javascript.

    • Brandon

      …Which explains why there aren’t jQuery, jQuery UI, Modernizr, or knockout.js packages….

      Except that there are and they work great.

  11. Tom

    Anyone figure out validation with Chosen yet? Racking my brain for a while now…

  12. Nguyen Teo

    Does this plugin support it’s own plugin? It doesn’t support Latin language (like Vietnamese) so I want to make some change.

    Thanks!

  13. arf

    I have proble in select by jquery

    $('select.foo option:selected').val('jq'); 
    $('#type').val('jq').data("selected","selected"); 
    $("#type option[value='jq']").attr("selected", "selected"); 
    

    all code cannot choose jquery chosen from jquery…It’s spinning my head

  14. It seems the best of the choices out there but it has no built in intelligence for when the option list traverses the browser boundaries. I have a time zone select box right at the bottom of our app. May have to modify or shop around more.

  15. Kirubaharan

    Great Plugin.
    How to validate this plugin with jquery validation. can any one help with this plz

  16. Jason

    Probably a noob question but how do you get the selected value off this? There’s no name attribute at all..

  17. Chosen ?

    I use chosen . One of the select option field filled by ajax
    I saw it in select option
    but cannot convert by chosen
    unless I wrote ajax success $(“.myclass”).chosen()
    watz the problem ?

    • Zia

      I am running the same issue ….
      – I am using ajax to fill a select box
      – run $(“.chzn-select”).chosen(); on ajax success.

      but its still not converted by chosen..

      can you please help me or show me your page where it is working..

      Thank you!

    • Gopi Sundharam

      Guys, after the AJAX call, add a delay (e.g: setTimeout) say 2 milli-seconds and then call the .chosen() on the newly added items/elements. This has worked for me.

    • use like

      $('selector').chosen('destroy');
      $('selector').chosen();
      

      When you are using ajax. it is work perfectly without spend time

  18. hi for this which jquery we have to choose

  19. I am using the js version of chosen and firing the function with $(".chosen").chosen();

    my problem is that I am using panels that open and close and when you doc read or window.load, like another modifying js script, the select does not exist so your have to fire the script when you slideDown the div in a function.

    When I fire it once it works great, when I fire it again, it does not work right, it can’t configure the with properly.

    Any suggestions.

  20. Pallavi

    Can anyone tells where is the source code available for this . I want to use the plugin as it as with my own data. But I am not getting exactly what Jquery code i need to put here. Please some one help. Its urgent

  21. anyone been able to make this do a ‘contains’ search instead of just a ‘starts with’ ?

    • BRENDAN

      Unsure if I am supposed to but I was able to change the code to do a global search instead of the starts with. Changed lines 738 and 739 to include ‘g’ for global and also took out the regexAnchor.

      New lines look like this

           regex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'gi');
            zregex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'gi');
      

      I have also included an anchor tag in my “no results” text which enables me to open a dialog to add a new item to the list and the refresh the list with the new object.

      Must give credits to the people who made this plug-in it is awesome…

      chosen.jquery version 0.9.8.

  22. Hi, great plugin!

    Just one thing to change about the search, about regexAnchor variable here:

          regexAnchor = this.search_contains ? "" : "^";
          regex = new RegExp(regexAnchor + searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');
          zregex = new RegExp(searchText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i');
    

    better way to do a contains search instead of just a ‘starts with’ is changing line 132:

    this.search_contains = (this.options.search_contains = "TRUE")? true : false;// modified from this.options.search_contains || false;

    i set true when wanna a ‘contain’ search and the ‘start with’ search still there when needed.

    Thank for this great plugin.

    • Sorry the above, i still learning about the options supported…

      	jQuery(".chosen").chosen({
      		no_results_text: "My language message.", 
      		placeholder_text : "My language message.", 
      		search_contains: true,
      		disable_search_threshold: 10
      	});
      

      …thank to people develop this.

  23. These select elements are the best ever. Which I d like to use it, but there are 2 types of select elements there:1-Single with search 2-Multiple with search. Can you add a 3rd one please:Just a simple select without search. Can you add a third type: Single select element without search facility and without search box, please. I really would appreciate it. – You might say so use any simple select element then. Yes but I d like to use 3 types of select elements in the same form. 1-Single with searc 2-Multiple with search and 3-Single without search facility and its search box. So I can have 3 typs and 3 of them can have those nice backgrounds and gradients and image arrow etc. I like the style of them. Thanx.

  24. Its great script.
    On your script there are 2 select element types: single and multiple. But you dont have one without the search facility. I need the 3rd one: just a simple select. Its gonna look like single type but without the search facility and search box. Basically I need a simple select element. You can say ok so just make one works without this script. But I just like it looks that can have gradient background on the drop down list area and select arrow. And on the same form I ll use single and multiple element types too. Therefore I need to use this script and its css. So please any comments how can I disable the search facility and to get rid off the search box? Thanx.

    • Tai Nguyen

      Why would you want to remove perfectly useful functionality? Yes, I understand you’re more interested in the styling of the select, but just leave the search in – your users will thank you for it.

  25. alfonso cataldi

    ciao, sull’evento onchange della select io costruisco un’altra select con ajax attraver so

    $.ajax({
    	type: "POST",
    	url: strUrl,
    	data: strData,
        success : function (data) {
    		$("#div_anotherSelect").html(data");
        },
        error : function (jqXHR, textStatus) {
            alert("E' evvenuto un errore: " + jqXHR.responseText );
        }
    });
    

    dove “data” è appunto la seconda select, come faccio per far diventare anche questa seconda select con il plugin di chosen.js ?

    grazie

  26. John Walton

    I would like to use Chosen with multiple options which are rather long phrases. So they won’t naturally fit into the option text box. Does Chosen expand the box height to fit? Or is there any other solution. I really need a line per option selected.

  27. Dhruval Dave

    How to select value from jQuery in Dropdown .?

  28. rory

    how do i reset the value of the dropdown?

  29. Due to the lack of proper documentation, I’ve wrote a short post about chosen and the custom event it triggers. Very handy if you tend to do some advanced coding with Chosen.

    http://forwebonly.com/jquery-chosen-custom-events-and-how-to-use-them/

  30. Hey Guyz,

    I have used chosen and its working fine, but I need to add new option to chosen plugin, user need a permission to add item dynamically in multi select :(

    • Etic

      That’s not what I wrote, use this instead to add item dynamically:

      jQuery('.chosen').append('New Option').trigger('liszt:updated');
      

      But after reading your question again, I think this is not what you are asking…
      You want to add new option to the Chosen plugin like

      jQuery('.chosen').chosen({ required_user_level: 'admin' }); ?
      
    • Etic

      Man! The comment box is cutting away my tags >:(

      Just to be clear, in the .append, you need to add the New Option

    • Etic

      Argghhhhh, look here instead (the above codes aren’t showing properly): http://jsfiddle.net/NQ4MN/1/

  31. Liviano

    Can i have tool tip for the drop down

  32. Zency

    Thanks for sharing,it works find. But how to update the data-placeholder like the options?

    • Etic

      Read below…

  33. suresh

    Hi all,

    I have developed one app using phone gap. In one screen i used chosen.jquery.js for drop down choose.It is working fine in all ios version and android version except jelly beam. For checking just opened example page (wed site page [http://harvesthq.github.io/chosen/][1]) in device browser it is working fine.But it is not working in app . Can any one help on this please.

  34. Mohammad Amin Abou Harb

    nice work!
    how do I add an on item added event or on item deleted event and is there a way to cancel the add/delete from those events?

  35. Thanos

    I get a problem with the chosen dropdowns coming out with a black background when using Chrome. When the option “Background colors and images” is selected while Printing on Chrome all the Chosen Dropdowns turn Black… Is there a work around this issue?

  36. Vipul

    hello, this chosen plugin not working with multiple select.

  37. Trianta

    Hi,
    I would like show more values.
    How i can show on drop down the title tag of option value?

    • html: option.innerHTML, // search
      title: option.title,    // add
      
      option_el.innerHTML = option.search_text;  // search
      option_el.title = option.title;            // add
      
  38. shekhar

    i to use this pluging for multiple drop down in single page…i want to customize all the drop down when page load it working fine for one drop down but for multiple it customizing the drop down but not appending the data for reset of the drop down…plz reply as soon as posible

  39. hetfy

    It won’t work when using jQuery’s clone method.

  40. hey its great but can you explain me how that search box came in dropdown.
    i am tring to build my own in joomla so i don’t know how i can add that search box. ?

  41. srinivas

    i wanted to show the Options with the images, How can we add images for each select box options…

  42. zhengqb

    there s a bug when used chinese in ubutun… match nothing

  43. ThePuiu

    I have a problem with this control when is placed on to a modal dialog (close to the bottom of the dialog). When combo is dropped down, his list does not exceded the limit of dialog’s but the dialog get a vertical scrollbar! How can i resolve this issue? Thank you!

    Btw, great job!

  44. Arif Hussain

    Hi Sir David Walsh !
    Of course the chosen plugin is awesome, but there is a (user interaction) problem, which I don’t know can be fixed or not.
    In the single select box, when I type mootools, it isolates MooTools from the list which is great (case-insensitive search), but than I must click on the MooTools or press the down arrow key to select it before pressing the enter, while now a days people are addicted to the practice of:
    1) Typing the starting characters of a word or sentence and than coming down the list by pressing down arrow key to select an option (or by clicking on that option) and than press enter, or
    2) To type the complete word or the sentence (without taking care of coming down to actually select the item from the list) and press enter.

    So the chosen plugin (as shown in the demo) is failed in the second case. Is it possible to overcome this problem ?

  45. Arif Hussain

    The problem I mentioned above is already solved in the new version of chosen plugin, thank you..

  46. pawan

    Hi
    I want to change the below line dynamically to implement the culture to pick from my .resx file or I could give the in if else condition. but when i tries to do so the chosen.jquery.js doesnot fetch completely. here is my code :-

    if ( culture =="no"
    AbstractChosen.default_multiple_text ="My text"
    else
    AbstractChosen.default_multiple_text ="Select Some option"
    

    Any help will be appreciated
    thanks
    Pawan

  47. Mike Anderson

    Mouse over doesnt work with chosen incase you want to show tool tip in option tag. Anyway of showing tool tip for dropdown list item

  48. bittu

    i want to load select box using ajax but this dropdown in file values

  49. locunhalima

    I want to add a new class that changes the back-color of the select created with chosen. On chosen load I pass inherit_select_classes: true.

    I tried to use jQuery('#my-select').trigger("chosen:updated"); after adding the class via jQuery, but it didn’t work.

    Thanks in advance.

  50. Senthilkumat

    i wanted to show the Options with the images, How can we add images for each select box options…

  51. Subha

    Hi all,
    When I place chosen on modal dialog it doesn’t work … anyone has workaround for this issue?

  52. Ranjan kumar Mohanty

    How to disable chosen element?

  53. Hi everyone,

    I’m using chosen(1.6) and facing a problem. Currently when select an option, it disabled. I want user can select the same option multiple times.

    Any idea? Please help

    Thanks

  54. Deeksha Gupta

    Hi

    I am working with the Jaws Screen Reader for the Web Accessibility. The problem, I am facing is Screen Reader does not read the select proper I am using the s-only text it doesn’t read that too. I only read “type and text”.

    Please help

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!