我使用以下代码添加国家/地区,用户从一个多选中选择国家并添加到另一个多选中,并在提交时将第二个多选的国家插入到数据库中。
.js
$(document).ready(function(){
$('.add').click(function(){
$('#country_list option:selected').appendTo('#country_select');
});
$('.remove').click(function(){
$('#country_select option:selected').appendTo('#country_list');
});
$('.add-all').click(function(){
$('#country_list option').appendTo('#country_select');
});
$('.remove-all').click(function(){
$('#country_select option').appendTo('#country_list');
});
$("#register").click(function() {
$("#country_select option").each(function() {
$(this).attr("selected", "selected");
});
});
});
.html
<select id="country_list" size="10" multiple style="min-width: 200px;">
<option value="US">United States</option>
<option value="UK">United Kingdom</option>
<option value="IN">India</option>
</select>
<table border="0">
<tr><td><input type="button" class='add' value=">"/></td></tr>
<tr><td><input type="button" class='remove' value="<"/></td></tr>
<tr><td><input type="button" class='add-all' value=">>>"/></td></tr>
<tr><td><input type="button" class='remove-all' value="<<<"/></td></tr>
</table>
<select size="10" name="country_select[]" id="country_select" multiple style="min-width: 200px;">
</select>
在这里,当点击添加按钮时,下拉国家/地区列表中的选定项目将移动到国家/地区选择。
我需要的是,当添加一个国家时,它应该按名称顺序移动到下拉国家/地区选择中。目前,当添加一个国家/地区时,它会位于国家/地区选项列表的底部。
最佳答案
每次移动选项时调用以下函数以重新排列 #country_select
中的选择选项按字母顺序
Js:
function reArrangeSelect() {
$("#country_select").html($("#country_select option").sort(function(a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
}
关于jquery - 使用 jquery 对多个选择下拉选项进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14018246/