12

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

John Ruddell
  • 25,283
  • 6
  • 57
  • 86

2 Answers2

17

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?

Community
  • 1
  • 1
dana
  • 17,267
  • 6
  • 64
  • 88
  • 1
    Thanks for your answer. I was going to just do it in javascript if there wasn't a method for it in the plugin, but you went ahead and wrote the javascript for me too! appreciate the help – John Ruddell Apr 30 '14 at 18:01
  • one thing I changed that you can change on here for others to see is i made the text lowercase for a complete alphabetic sort.. tolowercase() method :) thanks again for your help – John Ruddell May 16 '14 at 15:36
  • +1 for adding the source question of the `HTML Select Options sorting` – Adriano Sep 26 '14 at 15:19
  • 1
    i must commend you, dana for this code. it's refreshing when code works as directly plugged in. on to the next task, but this did the trick. – dcparham Jan 28 '15 at 14:39
  • If the dropdown is bound to a database field, the code above may change what was originally selected when the page loaded, so the dropdown no longer corresponds to the database value. To compensate for this, after the "var my_options" line above and before the sort, save the originally-selected value with `var orig_option = $("#my-dropdown option").val();` and then restore it after the empty().append() line with `$("#my-dropdown option").val(orig_option);` – Chirael Feb 22 '15 at 17:48
1

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
Jonathan Benn
  • 2,908
  • 4
  • 24
  • 28