Arkymedes
Arkymedes

Reputation: 179

How to sort fields in a <select> list but ignore one option

I have the following script that sorts the values of a list alphabetically because this list changes according to the language of the website.

<select style="width:250px" id="list1">
    <option value="">Confederation</option> <!--I would like to keep this at the top-->
    <option value="40934">Africa (CAF)</option>
    <option value="44624">Asia (AFC)</option>
    <option value="29521">Europe (UEFA)</option>
    <option value="43099">North &amp; Central America (CONCACAF)</option>
    <option value="46617">Oceania (OFC)</option>
    <option value="38731">South America (CONMEBOL)</option>
</select>

<script>
    $("#list1").html($("#list1 option").sort(function (a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
    }))
</script>

As you can see, after passing through the script, this is the output:

<select style="width:250px" id="list1">
    <option value="40934">Africa (CAF)</option>
    <option value="44624">Asia (AFC)</option>
    <option value="">Confederation</option> <!-- But it gets sorted also and it ends up in the middle -->
    <option value="29521">Europe (UEFA)</option>
    <option value="43099">North &amp; Central America (CONCACAF)</option>
    <option value="46617">Oceania (OFC)</option>
    <option value="38731">South America (CONMEBOL)</option>
</select>

The problem is that the first value that should be the first one gets sorted also so it ends up in the middle of the list and it looks awkward.

I would like to modify the javascript to exclude the first option value from the sorting, but keep it at the top. One thing to consider is that this first has a value of "" and it should be like that because I have another small script that forces the user to select anything else in order to process the form.

Thanks a lot in advance!

Upvotes: 6

Views: 4147

Answers (4)

palaѕн
palaѕн

Reputation: 73976

You can do this using the :gt() Selector:

$("#list1").append($("#list1 option:gt(0)").sort(function (a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
}));

This would select all options at an index greater than 0 within the matched set.

FIDDLE DEMO

Upvotes: 11

Ram
Ram

Reputation: 144739

You can use not method:

$("#list1 option").not(':first').sort(function(a, b) {
    return a.text > b.text;
}).appendTo('#list1');

http://jsfiddle.net/jgvfG/

Upvotes: 3

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

$("#list1").html(
    $("#list1 option:first")+    
    $("#list1 option:first").nextAll('option').sort(function (a, b) {
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
});)

Fiddle http://jsfiddle.net/HKJNb/

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74410

http://jsfiddle.net/Ljhpb/5/

$("#list1").html($("#list1 option").sort(function (a, b) {
    if(!a.value) return;
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
    }))

Upvotes: 0

Related Questions