Sort Options in HTML Select [duplicate]

跟風遠走 提交于 2021-02-08 10:12:09

问题


There is situation like this:

<select id="trollSelect">
    <option value="PL">Polish Troll</option>
    <option value="EN">English Troll</option>
    <option value="JP">Japanese Troll</option>
    [...] //more options created dynamically
</select>

Option values and Option texts are unsorted in Select. Is this possible to sort this options in JQuery or Javascript by value or text alphabetically ??

The result should be like that:

<select id="trollSelect">
    <option value="EN">English Troll</option>
    <option value="JP">Japanese Troll</option>
    <option value="PL">Polish Troll</option>
    [...] //more options created dynamically
</select>

回答1:


This code should do it. I've sorted them on their values but this can also be used to sort based on the text.

$(document).ready(function() {
    var opt = $("#trollSelect option").sort(function (a,b) { return a.value.toUpperCase().localeCompare(b.value.toUpperCase()) });
    $("#trollSelect").append(opt);
});

Here's a fiddle for the same



来源:https://stackoverflow.com/questions/23907833/sort-options-in-html-select

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