HTML Select With Selectable Option Groups and Multiple Hierarchies

HTML Select With Selectable Option Groups and Multiple Hierarchies

3 5706

Today I got to write a jQuery plugin that styles a select with hierarchical data. The markup would normally look like this in HTML:

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>

You can see the result of this over at w3schools

This looks cool, but what if you want to allow the user to select the optgroup telling the back end script to grab that level and all under it? I whipped up a quick plugin which works off of data attributes to describe the hierarchy. Here is what the structure of the html looks like:

<select id="hierarchySelect" class="form-control">
    <option data-isparent="true"  data-level="1">Main Dept 1</option>
    <option data-isparent="false" data-level="2">Sub 01</option>
    <option data-isparent="false" data-level="2">Sub 02</option>
    <option data-isparent="true"  data-level="2">Sub 03</option>
    <option data-isparent="false" data-level="3">Sub of Sub</option>
    <option data-isparent="true"  data-level="1">Main Dept 2</option>
    <option data-isparent="false" data-level="2">Sub 01</option>
    <option data-isparent="false" data-level="2">Sub 02</option>
    <option data-isparent="false" data-level="2">Sub 03</option>
</select>

The data-isparent should be flagged as true when there are child options under it. The plugin assumes that the options are already in the correct order. The data-level describes how many levels deep the option is. This assists in the indentation of the option. The default indentation is 25px, but can be overridden in the options of the plugin.

$("#hierarchySelect").selectHierarchy();

Here is a working fiddle that can be used to see the plugin in action.

Here is a link to Download the plugin. I want to build in some additional options and push it out to github when I have a chance. I will update this post when that happens. In the mean time, feel free to use it however you would like.

SIMILAR ARTICLES

0 2137

3 COMMENTS

  1. Thanks for this solutions, but your solution not working on chrome lastet version…This is working on firefox and safari…Please check it…Thanks…

Leave a Reply