在两个列表框之间对项目进行排序

时间:2018-04-26 15:57:07

标签: jquery

您好我有2个列表框的代码,我可以在列表框之间添加和移动项目...我的问题是如何在添加和删除项目后对项目进行排序

作为示例默认列表是12345后我将3添加到另一个列表框并将其删除它将变为12453而不是返回到12345



$(function() {
  $("#button1").click(function() {
    $("#list1 > option:selected").each(function() {
      $(this).remove().appendTo("#list2");
    });
  });

  $("#button2").click(function() {
    $("#list2 > option:selected").each(function() {
      $(this).remove().appendTo("#list1");
    });
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h3>List A</h3>
  <select name="list1[]" id="list1" multiple="multiple" rows=2>

    <option value=1>Option 1</option>
    <option value=2>Option 2</option>
    <option value=3>Option 3</option>
    <option value=4>Option 4</option>
    <option value=5>Option 5</option>
    <option value=6>Option 6</option>
  </select>
  <br/>
  <input id="button1" type="button" value="Move to List B" />
</div>
<div>
  <h3>List B</h3>
  <select name="list2[]" id="list2" multiple="multiple" rows=2>

  </select>
  <br/>
  <input id="button2" type="button" value="Move to List A" /> <br/>
  <input id="button3" type="submit" value="Save to database" />
</div>
&#13;
&#13;
&#13;

https://jsfiddle.net/cacaz0pj/

1 个答案:

答案 0 :(得分:1)

可以创建一个函数并在添加选项后调用它。您可以使用sort()

&#13;
&#13;
$(function() {
  $("#button1").click(function() {
    $("#list1 > option:selected").each(function() {
      $(this).remove().appendTo("#list2");
    });
    sortList("#list2");  //Call the function to sort #list2
  });

  $("#button2").click(function() {
    $("#list2 > option:selected").each(function() {
      $(this).remove().appendTo("#list1");
    });
    sortList("#list1");  //Call the function to sort #list1
  });


  //Function to sort options
  var sortList = function(id) {
    $(id).find('option').sort(function(a, b) {
      return a.innerText.localeCompare(b.innerText);
    }).appendTo(id);
  }

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <h3>List A</h3>
  <select name="list1[]" id="list1" multiple="multiple" rows=2>

    <option value=1>Option 1</option>
    <option value=2>Option 2</option>
    <option value=3>Option 3</option>
    <option value=4>Option 4</option>
    <option value=5>Option 5</option>
    <option value=6>Option 6</option>
  </select>
  <br/>
  <input id="button1" type="button" value="Move to List B" />
</div>
<div>
  <h3>List B</h3>
  <select name="list2[]" id="list2" multiple="multiple" rows=2>

  </select>
  <br/>
  <input id="button2" type="button" value="Move to List A" /> <br/>
  <input id="button3" type="submit" value="Save to database" />
</div>
&#13;
&#13;
&#13;

您还可以使用更短的代码:

$("#button1").click(function(){
    $("#list1 > option:selected").appendTo("#list2");
    sortList('#list2');
});

$("#button2").click(function(){
    $("#list2 > option:selected").appendTo("#list1");
    sortList("#list1");
});

`