Como ordenar listas de elementos

by hugoruscitti

HTML

<select id="lista" multiple="multiple" size="5">
  <option>Item 1</option>
  <option>Item 2</option>
  <option>Item 3</option>
  <option>Item 4</option>
  <option>Item 5</option>                        
</select>	
<br />
<br />

<input id="move-up" type="button" value="Move Up" />
<input id="move-down" type="button" value="Move Down" />    
<br />

JavaScript

$(document).ready(function() {
   $("#move-up").click(function () {moveUp('lista')});
   $("#move-down").click(function () {moveDown('lista')});
 });
 
 // Moving up the selected items
 function moveUp(id_lista) {
   // get all selected items and loop through each
   $("#" + id_lista + " option:selected").each(function() {
     var listItem = $(this);
     var listItemPosition = $("#" + id_lista + "  option").index(listItem) + 1;
 
     // when the item is already at the topmost,
     // we do not need to move it up anymore
     if (listItemPosition == 1) return false;
 
     // the following will move the item up
     // this inserts the listItem over the element before it
     listItem.insertBefore(listItem.prev());
   });
  }
 
  // Moving down the selected items
  function moveDown(id_lista) {
    // get the number of items
    // we will need this later to determine
    // if the item is at the bottommost already
    var itemsCount = $("#" + id_lista + " option").length;
 
    // for move down, we will need to start moving down items
    //   from the bottom
    // we get the selected items, reverse it then then loop each item
    $($("#" + id_lista + " option:selected").get().reverse()).each(function() {
      var listItem = $(this);
      var listItemPosition = $("#" + id_lista + " option").index(listItem) + 1;
 
     // when the item is already at the bottommost,
     //we do not need to move it down anymore
      if (listItemPosition == itemsCount) return false;
 
      // the following will move down the item
      // this inserts the listItem below the element after it
      listItem.insertAfter(listItem.next());
    });
  }