【问题标题】:Sorting multiple select dropdown options using jquery使用 jquery 对多个选择下拉选项进行排序
【发布时间】:2016-04-13 17:09:53
【问题描述】:

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

.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 但没有用。

【问题讨论】:

    标签: jquery html select


    【解决方案1】:

    每次选项移动时调用以下函数以按字母顺序重新排列 #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

    【讨论】:

      【解决方案2】:

      基于值的自定义元素排序器

      function optionSort(a, b) {
          return $(a).val() > $(b).val();
      }
      
      var opts = $('#selectID option').get();
      
      $('#selectID ').html(opts.sort(optionSort))
      

      演示:http://jsfiddle.net/5WgYK/

      【讨论】:

        【解决方案3】:

        如果您需要通过选择对多选进行排序,同时将所选项目保持在列表顶部,这将很有用。

        $('#identifier option:selected').prependTo('#identifier');
        $("#identifier").multiselect("refresh");  
        

        【讨论】:

          猜你喜欢
          • 2018-12-28
          • 1970-01-01
          • 2017-02-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-16
          • 1970-01-01
          • 2017-08-11
          相关资源
          最近更新 更多