Working with multi-select boxes in jQuery

harry.pottash's picture

Often, to make forms just a bit more usable, it's necessary to bring in jQuery to anticipate or assist some of the actions that the user is performing. Most of these changes are quite easy, but with some of the less-often used form elements, interaction can be surprisingly obscure.

One of the most atypical form elements is the multi-select box (also referred to as a listbox). When working with the multi-select box, simple jQuery calls like $("#Listbox").val("option_3") won't work. Instead it's necessary to work with the individual options within the listbox. They can be selected in bulk by using the statement $("#Listbox option"). Using this, it's possible to reach the value (though that's probably not what you want to do) and to select or unselect options by calling .attr("selected")

Some quick examples:

To select only the "cat" value, but leave all other options in there previous state you could use the following line:
$("#Listbox option[value='cat']").attr("selected","selected");

To de-select all of the entries you might use a line that looked like this:
$("#Listbox option").attr("selected",false);

Using the examples above, as well as variations and combinations of them, it should be possible to achieve most changes to select boxes with minimal aggravation.

Switchback Caravan logo

Caravan is a powerful and full-featured membership management system, designed specifically for membership- driven organizations.

Caravan Member Managment

Switchback Trailhead logo

Trailhead is a Drupal-based system, built with the features smaller businesses need, bundled together into a ready-to-launch package.

Trailhead CMS Packages

On the Trail Blog