jquery-bonsai is a lightweight jQuery plugin that takes a big nested list and prunes it down to a small expandable tree control.

Also includes support for checkboxes (including 'indeterminate' state) and for populating the tree using a JSON data source.

Examples

Create a Collapsible Tree from a Nested List

$('#music').bonsai();
  1. Instrumental Ensembles
    • String section
    • Brass and/or Horns sections
    • Percussion Sections
  2. Lyrical content
  3. Elements
  4. Other

A Tree with Checkbox Semantics

Checkboxes are handled using the jQuery Qubit library.

From Checkboxes in Markup

$('#checkboxes').bonsai({
  expandAll: true,
  checkboxes: true // depends on jquery.qubit plugin
});
  1. All
    1. One
    2. Two
      1. Three
        1. Four
      2. Five

Auto-Generated Checkboxes

Creates checkboxes for each list item. The name and value for the checkboxes are taken from data-name and data-value. The name is inherited from the parent items, if not specified. Checked state can be indicated using data-checked.

$('#auto-checkboxes').bonsai({
  expandAll: true,
  checkboxes: true, // depends on jquery.qubit plugin
  createCheckboxes: true // takes values from data-name and data-value, and data-name is inherited
});

The following markup...

<ol id='auto-checkboxes' data-name='foo'>
  <li class='expanded' data-value='0'>All
    <ol>
      <li data-value='1'>One</li>
      <li data-value='2'>
        Two
        <ol>
          <li data-name='baz' data-value='3'>
            Three
            <ol>
              <li data-name='baz' data-value='4' data-checked='1'>Four</li>
            </ol>
          </li>
          <li data-value='5'>Five</li>
        </ol>
      </li>
    </ol>
  </li>
</ol>
      

...yields:

Generate the Tree Using a JSON Data Source

Requires the JSON List plugin.

$('#from-JSON').jsonList({
  url: 'example.json',
  type: 'groupedItems',
  groups: 'locationGroups',
  items: 'locations',
  // onListItem: called for each list item created from the JSON
  onListItem: function(listItem, data, isGroup) {
    if( !isGroup )
      // set the id into a data value so that Bonsai createCheckboxes
      // can set the checkbox value
      listItem.attr('data-value', data.id);
  },
  // success: called after the list is created
  onSuccess: function(jsonList) {
    // turn the list into a tree
    $(this.el).find('> ol').bonsai({
      checkboxes: true,
      createCheckboxes: true,
      handleDuplicateCheckboxes: true,
      expandAll: true
    });
  }
});