Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I re-order the <options> alphabetically in a jquery-chosen dropdown

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

like image 474
John Ruddell Avatar asked Apr 30 '14 17:04

John Ruddell


People also ask

How do I sort a drop down list in alphabetical order in angular 6?

The sort function prototype is sort(compareFn?: (a: T, b: T) => number): this; with: Sorts an array. * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order.


1 Answers

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?

like image 90
dana Avatar answered Sep 20 '22 15:09

dana