Building a Single-Select List in jQuery

We needed a single-select list box for a web application we’re building. We also needed each item in the list to have rich formatting, so we didn’t want to use the built-in list box. I knew that jQuery UI had a Selectable widget that looked very promising. However we didn’t want multi-selection or the other advanced features it provides. I was somewhat surprised when I did a search on Bing that I didn’t find any guidance on how to create a single-select list box with jQuery. However I did find enough hints. It turned out to be really simple. If I were a more experience web developer, I probably would have known all of this. This blog post is for people like me who aren’t web experts yet.

The solution involves adding a custom data- attribute to each item in the list, creating CSS entries for hover and selected, and writing a single jQuery method that handles updating the section. In the example below, I’m using data-query on HTML elements, like this:

 @foreach (Query query in Model)
    <div data-query="@query.Key">@query.Name</div>

CSS Class

Next I added some CSS to display different colors for hover and selected:

    background-color: #EEF;
    cursor: pointer;

    background-color: #CCF;

The first entry changes the color and mouse pointer for the entry under the mouse. It does this by selecting all div elements that contain the data-query attribute. The second entry is simply a class that we’ll apply to the “selected” element using some jQuery code.

jQuery Code

The following jQuery code is all that you need:

 $("[data-query]").click(function () {
    // Do any work on the selected element

The first line removes the querySelected class from any elements that have the data-query attribute. This basically removes the highlighting from all elements in the list. The second line adds the querySelected class only to the element that received the click, basically highlighting that element.

In the rest of the click function, you can add other operations you might want to perform when you click on a list item.