Shaun
Shaun

Reputation: 2181

How do you sort an HTML drop down by the Option text, not the value?

When a user clicks a button, I'm loading extra genres into an HTML dropdown using jquery. I'd like to order the drop down in alphabetical order of the option text, not the value.

My php genre array looks like

$genres = array (0=>"All", 200=>"Pop", 201=>"Classic Rock", ...etc

The key numbers are loaded as the values in the drop down, while the text fills the options.

And my jquery

$.each(json, function(val, text)
{                   
    options[options.length] = new Option(text,val);
});

That displays in the drop down

All
Pop
Classic Rock

ie not in alphabetical order

My first plan was to sort the array in php, but on testing, even if the array is

 $genres = array (0=>"All", 201=>"Classic Rock", 200=>"Pop", ...etc

the drop down still displays

All
Pop
Classic Rock

How do I force it to order it in the order that it receives the json?

Thanks for your help.

Upvotes: 0

Views: 2362

Answers (2)

Prabandham Srinidhi
Prabandham Srinidhi

Reputation: 23

It would be better if the sorting is done in the server side (Or so I feel).

PHP has a couple of methods that let you sort based on KEY - (ksort) or value - (asort)

You could do this to your array :-

$genres = array (0=>"All", 200=>"Pop", 201=>"Classic Rock", ...etc
$stortedgeneres=$genres;
asort($stortedgeneres);

Then you can use your JavaScript on this array ($sortedgeneres) to loop through as before.

References:- http://www.w3schools.com/php/php_arrays_sort.asp

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try it like,

$(function(){
    var options = $("#select-box-id option");
    options.sort(function(a,b) {
        if (a.text > b.text) return 1; // .text for text comparison
        else if (a.text < b.text) return -1;
        else return 0
    });
    $("#select-box-id").html(options );
});

Live Demo

Upvotes: 3

Related Questions