selectList Home

selectList Documentation

Last revised: Jul 31, 2011

  1. Introduction
  2. Basic Usage
  3. Options
  4. Classes
  5. Callback Functions
  6. Custom Animations
  7. Custom Sorting
  8. Validation
  9. API Methods
  10. Known Issues

Introduction

SelectList is a jQuery plugin that transforms the traditional multiple select element used in web forms (which is usually displayed as a scrollable box of options) into a more user-friendly form. Instead of highlighting options in a box, the user selects items from a drop-down list, and each selected item is added to a list placed next to the drop-down element.

The major advantage of this approach is that all the selected options are shown at the same time. With the standard multiple selection box using a long list of options, the user is often forced to scroll the list to make sure all the desired options have been selected.

The alternative interface is fully compatible with the standard multiple select element. Any options pre-selected in the original select will be automatically added to the list of selected options when the plugin is initialized. When the form is submitted, the transmitted data is exactly the same as with the conventional select.

Basic Usage

The plugin is invoked by calling the selectList() method on a jQuery object that represents a <select> element:

$(document).ready(function () {
  $('select#someid').selectList();
});

If there is more than one element in the jQuery object, the plugin will be applied to all the <select> elements in the set.

If the <select> element has a title attribute, it will be used as a hint in the drop-down list.

Options

The plugin is highly customizable through the use of options which are passed to the selectList method when the plugin is initialized. The available options are:

Option Description
addAnimate If set to true, selected items are added to the list using a graceful animation (fadeIn(300)).
If set to false, new items appear instantly.
Can be set to a function that runs a custom animation (see below).
default: true
classPrefix A string that is prepended to class names assigned to plugin elements (see below for details).
default: "selectlist"
clickRemove If set to true, clicking on a selected item removes it from selection.
default: true
duplicates If set to true, the same item can be selected more than once.
If set to false, each item can only be selected once.
default: false
list A jQuery object, DOM element, or HTML string representing a list element which will be used as a container for selected items.
default: "<ul />"
removeAnimate Similar to addAnimate, but for removing.
If set to true, items are removed using a graceful animation (fadeOut(300)).
If set to false, items disappear instantly.
Can be set to a function that runs a custom animation (see below).
default: true
sort If set to true, the selected items are automatically sorted.
If set to false, the items appear in the order that they were selected.
If set to the string "desc", the selected items are sorted in descending order.
Can be set to a custom sorting function (see below).
default: false
template A HTML template that is used to create new elements representing the selected items. The string %text% is replaced by the label of the selected option, and %value% is replaced by its value.
default: "<li>%text%</li>"
onAdd Callback function called when an item is added to selection (see below)
onRemove Callback function called when an item is removed from selection (see below)

If you call the plugin again for the same <select> element with a new set of options, the new options will replace the old ones, and some options will be applied dynamically — for example, if you change the sort option from true to "desc", the selected elements will be re-sorted in descending order. Re-setting has no effect on the list option.

Classes

The plugin assigns classes to the elements that represent the selected items.

Class Name Assigned to
selectlist-select The single selection element (drop-down list) used to choose items
selectlist-list The list element containing the selected items
selectlist-item Each selected item

The default "selectlist" class prefix can be changed to something else using the classPrefix option. This might be useful when there are multiple plugins on one page and you want to apply different CSS styles to each of them.

Callback Functions

You can define callback functions that will be run when a new item is added to the selection (onAdd), and when a selected item is removed (onRemove).

The callback functions are passed three arguments. First argument is a reference to the <select> element, the second is the value of the item begin added/removed, and the third argument is the item's text. Here's an example of a callback function that might be executed after an item has been added:

$('select').selectList({
  onAdd: function (select, value, text) {
    alert(text + ' is a good choice, sir!');
  }
});

If there is animation when items are added/removed, the callback function will be run when the animation is completed.

Custom Animations

You can set the addAnimate or removeAnimate option to a function that does a custom animation instead of the default fadeIn/fadeOut.

The animation function takes two arguments: the first is a reference to the DOM element representing the selected item, the second is a callback function that MUST be called in your function when the animation is completed. If you're doing the animation with standard jQuery effects, then you simply need to forward the callback argument to the effect function — here's an example using slideUp and slideDown:

$('select').selectList({
  addAnimate: function (item, callback) {
    $(item).slideDown(500, callback);
  },
  removeAnimate: function (item, callback) {
    $(item).slideUp(500, callback);
  }
});

Custom Sorting

A custom sorting function can be used to arrange the selected items in the desired order. The function takes two arguments which are two DOM elements corresponding to the items being compared. The return value should be true if the first item is considered to be greater than the second one, or false otherwise.

Here's an example of a sorting function that compares the two items by their text converted to lowercase, resulting in case-insensitive sorting (by default, sorting is case-sensitive):

$('select').selectList({
  sort: function (item1, item2) {
    return $(item1).text().toLowerCase() > $(item2).text().toLowerCase();
  }
});

Validation

The jQuery Validation plugin can be used with selectList, allowing you to dynamically validate the options selected by the user. For example, the required rule makes sure the user selected at least one option, and the maxlength rule limits the maximum number of options that can be selected:

$('select[name="something"]').selectList();

$('form').validate({
  rules: {
    something: { required: true, maxlength: 3 }
  },
  messages: {
    something: {
      required: "Please select at least one option",
      maxlength: "Whoa whoa, you can't select more than 3 options"
    }
  }
});

There is, however, one caveat. By default, the validation plugin marks invalid input/select elements by adding the "error" class to them. In the case of selectList, the actual multiple selection element is hidden in the document, and adding the error class to it has no visual effect. The class should be applied to the drop-down list instead.

The following piece of code takes care of this — the functions provided for highlight and unhighlight check if the element being marked as valid or invalid is a multiple selection element with selectList attached to it, and if it is, they use the next element instead (the drop-down list). There's also an errorPlacement function which does the same thing to ensure that the error message is placed next to the drop-down.

$('form').validate({
  ...
  highlight: function (element, errorClass, validClass) {
    if ($(element).data("selectList"))
      element = $(element).next().get(0);
      
    $(element).addClass(errorClass).removeClass(validClass);
  },
  unhighlight: function (element, errorClass, validClass) {
    if ($(element).data("selectList"))
      element = $(element).next().get(0);
               
    $(element).removeClass(errorClass).addClass(validClass);
  },
  errorPlacement: function (error, element) {
    if (element.data("selectList"))
      element = element.next();

    error.insertAfter(element);
  }
});

API Methods

SelectList provides a number of API methods to make it easier to extend and integrate the plugin with other web application components.

To make use of these methods, you need an instance of the plugin's object. To get one, call the selectList() method with the instance option set to true:

var sl = $('select').selectList({ instance: true });

You can use the resulting object to call the available public methods. For example, the following call adds a new item to the selection, with a value of 2 and the label "Foo":

sl.add(2, "Foo");

The plugin provides the following methods:

Method Description
setOptions setOptions(newOptions)

Set plugin options

Parameters:
newOptions – The new options object

val val()

Get currently selected options, similar to using the core jQuery .val() method on a regular multiple selection element.

Returns:
An array of values corresponding to the selected options

Note: Since selectList 0.4, the jQuery .val() method can be used with a selectList-enabled multiple selection element. This method is kept for backwards compatibility.

add add(value, text)

Add a new item to the selection

Parameters:
value – The value of the new item
text – The label text

remove remove([value])

Remove the item with the given value from the selection. If more than one item has the specified value, they will be all removed. If value is not given, all selected items will be removed.

Parameters:
value (optional) – The value of the item(s) to be removed

Known Issues

There is a minor bug that occurs in Firefox — if you select an option from the drop-down list, then expand the list again, move the mouse cursor over some other option (without clicking), close the list by clicking outside it, then the highlighted option will be added to the selection when the drop-down element loses focus. So far, I haven't figured out why this happens.