Automatic sort of custom drop down lists | Community
Skip to main content

Automatic sort of custom drop down lists

  • August 7, 2025
  • 1 reply
  • 0 views

Bob14

I'm trying to add a jQuery function to our theme that will automatically sort a custom dropdown list. I can do it with the baseline dropdown lists such as request priority since they use the HTML option element. But custom drop down lists appear to group their items using an array attribute named data-tagger. Is sorting a custom dropdown list using a jQuery function in our theme doable?

1 reply

Greg29
  • August 7, 2025

Hi Bob! I played around with this for a while today and was hitting some walls, but I came up with a solution that uses templating version 4. This is just a basic and stripped down example that sorts all of the drop-down fields, so you would want to update this for your specific needs…plus it might not work in every scenario, so test it out! But I got it working, so give it a whirl:

 

<script>
  (function($) {
    $(document).ready(function() {
      $(document).on('click', '[role="combobox"]', function() {
        setTimeout(function() {
          var $listbox = $('[role="listbox"]:not([aria-hidden="true"])');
          if ($listbox.length) {
            var $options = $listbox.find('[role="option"]');
            if ($options.length > 1) {
              var $firstOption = $options.first();
              var $otherOptions = $options.slice(1);
              var sortedOptions = $otherOptions.toArray().sort(function(a, b) {
                return $(a).text().trim().localeCompare($(b).text().trim());
              });
              $.each(sortedOptions, function(_, option) {
                $listbox.append(option);
              });
            }
          }
        }, 10);
      });
    });
  })(jQuery);
  </script>