Sorting a Listbox with jQuery

Printer-friendly version

One of the web pages for a recent project required the use of several listboxes and I found myself needing a way to quickly sort a given listbox due to the large number of options in some cases. Changing the underlying data source would certainly work for say, ascending order (and I did do that), but what if you wanted to toggle between ascending and descending? I could used Ajax, but since the sorting was only to aid selecting an item, I decided to just use jQuery client-side. The following is an example of a listbox with several options and a button to perform the sort. [code language="html"] <select size="4" name="lbCarrier" id="lbCarrier" class="listbox"> <option value="0">None</option> <option value="8">Principal</option> <option value="14">Other</option> <option value="3">Cigna</option> <option value="2">Blue Cross</option> <option value="11">Trustmark</option> <option value="10">Starmark</option> <option value="1">Atena</option> <option value="5">Humana</option> </select> <input type="submit" id="btnSortItems" value="Sort Items" /> [/code] Using jQuery I simply wired up a handler for the SortItems button click event and added a Sort function to do the work. [code language="javascript"] $(function() { $("#btnSortItems").click(function(e) { e.preventDefault(); Sort("lbCarrier"); }); }); function Sort(elementId) { // Convert the listbox options to a javascript array and sort (ascending) var sortedList = $.makeArray($("#" + elementId + " option")) .sort(function(a, b) { return $(a).text() < $(b).text() ? -1 : 1; }); // Clear the options and add the sorted ones $("#" + elementId).empty().html(sortedList); } [/code] To sort descending, you simply reverse the operator in the comparison as shown below. You can also sort the listbox by the option value using $(a).val() > $(b).val() but that's not as meaningful since those values aren't visible and if the values are actually numbers, as in my case, they won't sort properly because they are treated as strings. [code language="javascript"] // Descending sort return $(a).text() < $(b).text() ? -1 : 1; [/code] Once the sorting is complete, you may want to select an option based on it's Text, Value or Index. Here are a few of the many different ways to select an option. [code language="javascript"] // Select by Text $("#lbCarrier").find("option:contains('Other')").attr("selected", "selected") // Select by Value $("#lbCarrier option[value='8']").attr("selected", "selected") // Select by Index $("#lbCarrier option").eq(3).attr("selected", "selected") // Select the first option $("#lbCarrier option:first").attr("selected", "selected") [/code] For my actual implementation, I wired up the listbox dblclick event to so that I could easily toggle between ascending and descending sorts instead of using a button, but the process is basically the same and it works for the standard select list/combobox as well. jQuery makes it easy to add functionality or quickly try things out, it reduces the amount of code you would typically have to write and makes working with JavaScript something to look forward to instead of dreading.

About the Author:

TopLine Strategies delivers the complete integration and development of sales, marketing and customer service technologies that enable corporate clientele to improve revenue streams and strengthen customer interactions. Our project management and consulting is designed to achieve timely delivery, 100 percent user adoption of the technologies we implement and deliver measurable returns on investments for our clients.

 

Comments (0)

Related Blogs

TheReact Native Open Source roadmap was announced in Q4 2018 after they decided to invest more in the React Native open source community.

October is not just about pumpkins, fall foliage, and cooler temps anymore. October 2018 also means the exciting introduction of Microsoft Dynamics 365 for Customer Engagement.

Back in 2016, Microsoft introduced its intentions to refresh its CRM and ERP strategy with Dynamics 365. At the heart of its services was the Common Data Model (CDM).