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

时间:2012-12-24 07:10:49

标签: 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但没有工作。

3 个答案:

答案 0 :(得分:2)

每次选项移动以按{0}按字母顺序重新排列选择选项时,请调用以下函数

JS:

#country_select

Live Demo | Source | Credit

答案 1 :(得分:1)

基于值的自定义元素分类器

function optionSort(a, b) {
    return $(a).val() > $(b).val();
}

var opts = $('#selectID option').get();

$('#selectID ').html(opts.sort(optionSort))

DEMO:http://jsfiddle.net/5WgYK/

答案 2 :(得分:0)

如果您需要按照所选项对多选项进行排序,同时将所选项目保留在列表顶部,这将非常有用。

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