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

左心房为你撑大大i 提交于 2019-12-09 12:57:53

问题


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!


回答1:


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




回答2:


You can use not method:

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

http://jsfiddle.net/jgvfG/




回答3:


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
    }))



回答4:


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/



来源:https://stackoverflow.com/questions/16895139/how-to-sort-fields-in-a-select-list-but-ignore-one-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!