Today I was presented with a Magento configurable product that has options that were not appearing in order when you clicked the drop down. A quick look with Firebug showed me that the drop down option values would be in proper alpha numeric order if I simply sorted the values of the options. First thing I thought to do is fix it with jQuery. So I created and uploaded a JavaScript file with a jQuery function I found online for sorting the options by value. Here’s the contents of that file:


      jQuery.fn.sortOptionsByValue = function()
      {
      var byValueSortCallback = function(x, y)
      {
      var xVal = jQuery(x).val();
      var yVal = jQuery(y).val();
      return (xVal < yVal) ? -1 : (xVal > yVal) ? 1 : 0;
      };
      return this.sortOptions(byValueSortCallback);
      };

Next thing I did was open up my Magento layout/catalog.xml file and locate the XML block that begins with catalog_product_view. Below that you will find a reference name=”head”. In there I inserted the following action which includes the JavaScript file I created and mentioned above:


<action method="addJs"><script>jQuery/sortselectbox.js</script></action>

In order to specifically fix the option order on this one configurable product I opened up that product in the Magento backend and inserted the following javascript into the product’s short description:


<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery('#attribute965').sortOptionsByValue();
  jQuery('#attribute965').val('').attr({selected: 'selected'});
});
</script>

This script will sort the options by value alpha numerically (a-z0-9) and then it will put the empty option for “Choose an Option” as the first option and sets selected=”selected” on that option. From there you should be good to go. If you have a much more elegant method to resolving this feel free to let me know.

Leave a Reply