jquery - 使用 jquery 对多个选择下拉选项进行排序

标签 jquery html select

我使用以下代码添加国家/地区,用户从一个多选中选择国家并添加到另一个多选中,并在提交时将第二个多选的国家插入到数据库中。

.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>

在这里,当点击添加按钮时,下拉国家/地区列表中的选定项目将移动到国家/地区选择。

我需要的是,当添加一个国家时,它应该按名称顺序移动到下拉国家/地区选择中。目前,当添加一个国家/地区时,它会位于国家/地区选项列表的底部。

我试过这个 Javascript to sort contents of select element但不工作。

最佳答案

每次移动选项时调用以下函数以重新排列 #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
    }))
}

Live Demo | Source | Credit

关于jquery - 使用 jquery 对多个选择下拉选项进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14018246/

相关文章:

javascript - 点击div切换动画?

html - IE7 HTML/CSS margin-bottom 错误

mysql - 替换select语句mysql中不同位置的多个关键字

C# 林奇 : Dynamically create property and values that includes sum of a value from a grouped query

c# - C# 中的动态 Select 语句到 MySQL 数据库?

javascript - 使用 jQuery 查找多个类

javascript - DOM如何获取Knockout JS值

jQuery - 多个 :not selector

html - 如何使用 CSS 格式化 HTML 以进行列布局

javascript - 单击链接时如何将整个页面加载到 div 中?