[英]Sort by name in Select2
Is there any way to sort my list generated by select2 by name? 有什么方法可以按名称对由select2生成的列表进行排序? I have some code :
我有一些代码:
var dataUser = [{
"id": "5",
"text": "BTest"
}, {
"id": "2",
"text": "ATest"
}, {
"id": "8",
"text": "CTest"
}, {
"id": "13",
"text": "DTest"
}];
$("#mylist").select2({
data: dataUser,
templateResult: function(data) {
return data.text;
},
sorter: function(data) {
return data.sort();
}
});
http://jsfiddle.net/oe9retsL/4/ http://jsfiddle.net/oe9retsL/4/
This list sorts by id, but I want sort by text. 此列表按ID排序,但我想按文本排序。
You need to provide a function to sort()
which contains the logic to compare the text
property of each object in the array. 您需要提供一个
sort()
函数,该函数包含比较数组中每个对象的text
属性的逻辑。 Try this: 尝试这个:
sorter: function(data) {
return data.sort(function(a, b) {
return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
});
}
To sort the selected options you need to implement similar logic on the tag well when an option is selected, like this: 要对选定的选项进行排序,您需要在选择一个选项时在标签上很好地实现类似的逻辑,如下所示:
$("#mylist").select2({
data: dataUser,
templateResult: function(data) {
return data.text;
},
sorter: function(data) {
return data.sort(function(a, b) {
return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;
});
}
}).on("select2:select", function (e) {
$('.select2-selection__rendered li.select2-selection__choice').sort(function(a, b) {
return $(a).text() < $(b).text() ? -1 : $(a).text() > $(b).text() ? 1 : 0;
}).prependTo('.select2-selection__rendered');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.