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 & 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 & 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!
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
You can use not
method:
$("#list1 option").not(':first').sort(function(a, b) {
return a.text > b.text;
}).appendTo('#list1');
http://jsfiddle.net/jgvfG/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With