Display Option Paths In Select Boxes - jQuery selectPath

File Size: 3.66 KB
Views Total: 79
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Display Option Paths In Select Boxes - jQuery selectPath

When you have multiple option groups in a <select> element, it's easy to lose track of the context once an option is selected. 

The selectPath jQuery plugin is designed to display the path to the optgroup to which the currently selected option belongs right inside the select box. Similar to breadcrumbs in web design.

For example, if you select 'JavaScript' which is under the 'Languages' optgroup, selectPath will show 'Languages > JavaScript' in the <select> element. This prevents confusion when options share the same name in different optgroups.

How to use it:

1. Download and import the selectpath.js script into your jQuery project.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/selectpath.js"></script>

2. Call the function on your <select> element and the plugin will do the rest.

<select>
  <optgroup label="Group 1">
    <option>Option 1</option>
    <option>Option 2</option>
  </optgroup>
  <optgroup label="Group 2">
    <option>Option 1</option>
    <option>Option 2</option>
  </optgroup>
  ...
</select>
$(function() {
  // By default the separator is '/'
  $('select').selectPath()
})

3. Change the separator at runtime.

$(function() {
  $('select').selectPath({
    // Use the last selected separator or ' > ' as default
    separator: localStorage.getItem('select.advanced.lastSep') || ' > '
  })
  .on('change', function() {
    if($(this).val().startsWith(' ')) {
      $(this).selectPath('option', 'separator', $(this).val())
      localStorage.setItem('select.advanced.lastSep', $(this).val())
    }
  })
})

This awesome jQuery plugin is developed by core1024. For more Advanced Usages, please check the demo page or visit the official website.