我正在尝试按字母顺序理解option
元素中的select
个元素。理想情况下,我想把它作为一个单独的函数,我可以传入select元素,因为当用户点击某些按钮时需要对它进行排序。
我一直在寻找一种很好的方法,但是找不到任何对我有用的东西。
选项元素应按字母顺序按文本排序,而不是值。
这有可能吗?
答案 0 :(得分:103)
我要做的是:
<option>
的文本和值提取到对象数组中; <option>
元素。要用jQuery做到这一点,你可以这样做:
var options = $('select.whatever option');
var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
options.each(function(i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
编辑 - 如果您要排序以忽略字母大小写,则可以在比较之前使用JavaScript .toUpperCase()
或.toLowerCase()
函数:
arr.sort(function(o1, o2) {
var t1 = o1.t.toLowerCase(), t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
答案 1 :(得分:48)
在所有情况下,接受的答案都不是最好的,因为有时候你想要坚持选择类和不同的参数(例如data-foo)。
我的解决方案是:
var sel = $('#select_id');
var selected = sel.val(); // cache selected value, before reordering
var opts_list = sel.find('option');
opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
sel.html('').append(opts_list);
sel.val(selected); // set cached selected value
//对于ie11或获得空白选项的人,替换html('')empty()
答案 2 :(得分:28)
<select id="mSelect" >
<option value="val1" > DEF </option>
<option value="val4" > GRT </option>
<option value="val2" > ABC </option>
<option value="val3" > OPL </option>
<option value="val5" > AWS </option>
<option value="val9" > BTY </option>
</select>
$("#mSelect").append($("#mSelect option").remove().sort(function(a, b) {
var at = $(a).text(), bt = $(b).text();
return (at > bt)?1:((at < bt)?-1:0);
}));
答案 3 :(得分:22)
<select id="list">
<option value="op3">option 3</option>
<option value="op1">option 1</option>
<option value="op2">option 2</option>
</select>
var options = $("#list option"); // Collect options
options.detach().sort(function(a,b) { // Detach from select, then Sort
var at = $(a).text();
var bt = $(b).text();
return (at > bt)?1:((at < bt)?-1:0); // Tell the sort function how to order
});
options.appendTo("#list"); // Re-attach to select
我使用了tracevipin的解决方案,这种解决方案非常有用。我在这里为像我这样喜欢找到易于理解的代码的人提供了一个稍微修改过的版本,并在理解之后将其压缩。我还使用.detach
而不是.remove
来保留选项DOM元素的任何绑定。
答案 4 :(得分:4)
以下是@Alexey's solution的改进版本:
function sortSelectOptions(selector, skip_first) {
var options = (skip_first) ? $(selector + ' option:not(:first)') : $(selector + ' option');
var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value, s: $(o).prop('selected') }; }).get();
arr.sort(function(o1, o2) {
var t1 = o1.t.toLowerCase(), t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
options.each(function(i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
if (arr[i].s) {
$(o).attr('selected', 'selected').prop('selected', true);
} else {
$(o).removeAttr('selected');
$(o).prop('selected', false);
}
});
}
该函数具有skip_first
参数,当您想要将第一个选项保持在最前面时,此参数很有用,例如什么时候“选择以下:”。
它还会跟踪之前选择的选项。
使用示例:
jQuery(document).ready(function($) {
sortSelectOptions('#select-id', true);
});
答案 5 :(得分:2)
我知道这个话题很老但我认为我的答案对很多人都有用。
这是使用ES6从 Pointy 的答案制作的jQuery插件:
/**
* Sort values alphabetically in select
* source: http://stackoverflow.com/questions/12073270/sorting-options-elements-alphabetically-using-jquery
*/
$.fn.extend({
sortSelect() {
let options = this.find("option"),
arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort((o1, o2) => { // sort select
let t1 = o1.t.toLowerCase(),
t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
options.each((i, o) => {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
}
});
使用非常简单
$("select").sortSelect();
答案 6 :(得分:1)
jquery.selectboxes.js插件有一个排序方法。您可以实现该插件,或深入了解代码以查看对选项进行排序的方法。
答案 7 :(得分:1)
这些答案都不适合我。出于某些奇怪的原因,当循环选项时,每个选项在调用text()
时都不返回任何内容。相反,我被迫通过attr('label')
/**
* Sort the options of the target select list
* alphabetically by label. For some reason, when
* we call detach(), the returned options have no
* text() and instead we're forced to get the option's
* label via the 'label' attribute.
* @param select jQuery selector
*/
function sort_multi_select(select) {
var options = select.find('option');
options.detach().sort(function (a, b) {
var at = $(a).attr('label'), //label, not text()
bt = $(b).attr('label');
return at > bt ? 1 : at < bt ? -1 : 0;
});
options.appendTo(select);
}
//example
sort_multi_select($('#my_select'));
答案 8 :(得分:0)
这将为您提供在需要时手动重新排列的选项
How would you dynamically order an <option select> list using JQuery?
答案 9 :(得分:0)
是的,您可以按文字对选项进行排序,然后将其追加到选择框中。
function NASort(a, b) {
if (a.innerHTML == 'NA') {
return 1;
}
else if (b.innerHTML == 'NA') {
return -1;
}
return (a.innerHTML > b.innerHTML) ? 1 : -1;
};
答案 10 :(得分:0)
Malakgeorge答案很好,可以很容易地包装成jQuery函数:
$.fn.sortSelectByText = function(){
this.each(function(){
var selected = $(this).val();
var opts_list = $(this).find('option');
opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
$(this).html('').append(opts_list);
$(this).val(selected);
})
return this;
}
答案 11 :(得分:0)
我结合了marxin's和kuxa's的出色答案,以创建一个jQuery自定义函数
按选项的文本值(不区分大小写)对这些选项进行排序
保留所有已选择的值和
返回对其执行功能的原始jQuery对象:
$.fn.extend({
sortSelect() {
return this.each(function(){
let $this = $(this),
original_selection = $this.val(),
$options = $this.find('option'),
arr = $options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort((o1, o2) => {
// sort select
let t1 = o1.t.toLowerCase(),
t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});
$options.each((i, o) => {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
$this.val(original_selection);
})
}
});
Working example on jsFiddle is available at https://jsfiddle.net/jhfrench/64och25e/。