Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 749
Arkymedes Avatar asked Jun 03 '13 10:06

Arkymedes


2 Answers

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

like image 108
palaѕн Avatar answered Nov 12 '22 16:11

palaѕн


You can use not method:

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

http://jsfiddle.net/jgvfG/

like image 2
undefined Avatar answered Nov 12 '22 17:11

undefined