jQuery – Sort Element

I found a very good example which demonstrate how to sort elements in HTML using jQuery. It is too perfect to make any changes of it. Try it by yourself. But please note that the sort() function only works in jQuery 1.3.2 or above.

<html>
  <head>
    <title>jQuery Sort</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      /**
       * This example is create by ppolyzos
       * Reference: http://ppolyzos.com/2010/07/how-to-sort-a-drop-down-list-select-using-jquery/comment-page-1/#comment-780
       * 
       * The example is so straight forward and clear and i can't make any changes to make it more perfect.
       * Thanks ppolyzos.
       */
      $(document).ready(function() {
        // Add a last option to the cities drop down list
        $("#cities").append($('<option/>').attr('value', '1').text('Rome'));
 
        /* Either sory by name or by value, comment one of them. */

        // Sort by name
        $("#cities").html($("#cities option").sort(function (a, b) {
          return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
        }));
 
        // Sort by Value
        // If you don't convert a.value to integers javascript will assume
        // that a.value and b.value are strings
        $("#cities").html($("#cities option").sort(function (a, b) {
          var aValue = parseInt(a.value);
          var bValue = parseInt(b.value);
          // ASC
          //return aValue == bValue ? 0 : aValue < bValue ? -1 : 1;
          // DESC
          return aValue == bValue ? 0 : aValue > bValue ? -1 : 1;
        }));
 
        // Select an option
        $('#cities').val('3');
      });
    </script>
  </head>
  <body>
	  <select id="cities">
      <option value="0">Select City</option>
      <option value="2">Paris</option>
      <option value="3">London</option>
      <option value="4">Athens</option>
      <option value="5">Mexico</option>
    </select>
  </body>
</html>

 

Not much thing to say as the code has said it all. Thanks ppolyzos.

Done =)

Reference:

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.