Question

I have a dropdown that works just fine for what I need. The only issue I have is for all intents and purposes I cannot provide a sorted list to the dropdown, but need to order it alphabetically on the client side. I can't seem to find anything related to rearranging the tags by their value alphabetically in the chosen plugin. curious if anyone has had to do this or can point me in the right direction. sample code would be:

$("#my-dropdown").chosen({no_results_text: "No results matched"});

just wondering if theres an option to organize it before I go into ordering it myself in javascript. thanks in advance

Was it helpful?

Solution

You should sort the list first... Then run the chosen plugin.

// sort list
var my_options = $("#my-dropdown option");
my_options.sort(function(a,b) {
    if (a.text > b.text) return 1;
    else if (a.text < b.text) return -1;
    else return 0
})
$("#my-dropdown").empty().append(my_options);

// run chosen plugin
$("#my-dropdown").chosen({no_results_text: "No results matched"});

List sorting code pilfered from the highly rated answer here:

What is the most efficient way to sort an Html Select's Options by value, while preserving the currently selected item?

OTHER TIPS

Looking at the API, I don't see any sorting option either. However, here are two links that could be helpful:

  1. Ricky Rosario blog post of how to sort the select options
  2. jQuery Chosen Sortable project
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top