使用JS / Jquery对List国家/地区排序

时间:2016-04-26 09:34:59

标签: javascript jquery html jsp drop-down-menu

您好我需要对国家/地区列表进行排序,以便法国始终位于列表的首位。

以下是列表的输入顺序。

<select id="countriesList" name="countriesListName">
  <option value="US">USA</option>
  <option value="DE">Germany</option>
  <option value="FR">France</option>
  <option value="DM">Denmark</option>
  <option value="">Choose Countries</option>
</select>

3 个答案:

答案 0 :(得分:4)

  1. 我对选项进行排序
  2. 我将法国移至顶端
  3. 我移动&#34;选择Coumtries&#34;顶部(可能不需要,因为它的值是空的)
  4. 我选择&#34;选择Coumtries&#34; //你可以在这里选择FR
  5. &#13;
    &#13;
    $(function() {
      var $list = $("#countriesList"), $opts = $("option",$list);
      $opts.sort(function(a, b) {
        a = $(a).val();
        b = $(b).val();
        if (a > b) return 1;
        if (a < b) return -1;
        return 0;
      });
      $list.html($opts);
      // insertBefore or prepend
      $('option[value = "FR"]', $list).insertBefore($("option", $list).first());
      $('option[value = ""]', $list).insertBefore($("option", $list).first());
      $list.get(0).selectedIndex=0; // or 1 to select France
    });
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <select id="countriesList" name="countriesListName">
      <option value="US">USA</option>
      <option value="DE">Germany</option>
      <option value="FR">France</option>
      <option value="DM">Denmark</option>
      <option value="">Choose Countries</option>
    </select>
    &#13;
    &#13;
    &#13;

答案 1 :(得分:0)

完整的解决方案:

&#13;
&#13;
$(function() {

  var options = $('#countriesList option');

  options.sort(function(a, b) {

    if (a.value > b.value) {

      return 1;
    }
    else if (a.value < b.value) {

      return -1;
    }
    else {

      return 0;
    }
  })

  $("#countriesList").empty().append(options);

  // Vive la France!

  $('#countriesList option[value="FR"]').insertAfter($('#countriesList option:first'));

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="countriesList" name="countriesListName">
  <option value="US">USA</option>
  <option value="DE">Germany</option>
  <option value="AZ">Azerbaijan</option>
  <option value="FR">France</option>
  <option value="DM">Denmark</option>
  <option value="">Choose Countries</option>
</select>
&#13;
&#13;
&#13;

在:

enter image description here

后:

enter image description here

Demo at sfiddle.net

答案 2 :(得分:0)

function myFunction(country) {
    var select = document.getElementById("selectFrance");
    var opts = select.options.length;
    if ((select.options[1].value !== "FR")){
        for (var i=0; i<opts; i++){
            if (select.options[i].value == "FR"){
                select.insertBefore(select[i],select[1]); 
                break;
            }
        }
    }  
}