3

次のコードを使用して、ユーザーが1つの複数選択から国を選択し、別の複数選択に追加し、送信時に2番目の複数選択の国がデータベースに挿入される国を追加しています。

.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-optionsのリストの一番下に移動します。

このJavascriptを試して、select要素のコンテンツを並べ替えましたが、機能しませんでした。

4

3 に答える 3

2

オプションが移動するたびに次の関数を呼び出して、選択したオプションを#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
    }))
}

ライブデモ| ソース| クレジット

于 2012-12-24T07:24:14.437 に答える
1

値に基づくカスタム要素ソーター

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

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

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

デモ: http://jsfiddle.net/5WgYK/

于 2012-12-24T07:28:06.177 に答える
0

選択したアイテムをリストの一番上に保ちながら、選択した複数選択をソートする必要がある場合、これは便利です。

$('#identifier option:selected').prependTo('#identifier');
$("#identifier").multiselect("refresh");  
于 2016-04-13T09:09:53.873 に答える