Select2 is one of the most popular select list plugin for jQuery. It has beautiful features and powerful customization options.
One missing feature of Select2 is built-in support for making select boxes cascading/dependent. In simple words, loading/refreshing options of a select2 list box using ajax based on selection of another select2 list box. So, I’ve written a reusable class for this purpose.
Get it here – Select2 Cascade (for v4.x)
Looking for a demo?
Here is it – live demo.
Thanks to Codepen, JSON Blob and Twitter Bootstrap for making demonstration so easy!
How to use
Simple.. just need to create a new instance of Select2Cascade
by passing the following 3+1 things –
- Parent select2 listbox
- Child select2 listbox
- URL to load child items from
- (OPTIONAL) select2 options
To set the parent selected value in ajax request, keep :parentId: as a placeholder in url. The selected value of parent select2 listbox will replace the :parentId: string in url. For example –
Query string: /path/to/api?type=childType&parent_id=:parentId:
RESTful url: /path/to/api/items/:parentId:/sub-items
Another important point is, the response of ajax call MUST be a flat json object of value:label
pairs. e,g,
{ "20150415" : "Chittagong Zila", "20190901" : "Comilla Zila", "20221601" : "Cox's Bazar Zila", "20301401" : "Feni Zila" }
Otherwise, you have to adjust populating of options
as per your response data.
Examples
Let’s say, our requirement is – when selection of #parentList
is changed, send ajax call to path/to/api/categories?parent_id=SELECTED-PARENT-VAL
and set the options of #childList
from the ajax response. Then sample usages will be –
var select2Options = { width: 'resolve' }; new Select2Cascade($('#parentList'), $('#childList'), '/api/categories?parent_id=:parentId:', select2Options);
That’s all! The childList values will now load based on the selection of parentList instantly. Even, you can chain the dependency like this –
new Select2Cascade($('#district'), $('#zilla'), '/api/geocode/district/:parentId:/zilla'); new Select2Cascade($('#zilla'), $('#thana'), '/api/geocode/zilla/:parentId:/thana');
Oh wait.. there’s more!
If you want to do something with the response data or select boxes (after loading options), you can set (any number of) callbacks to be executed after the child listbox refreshed –
var cascadLoading = new Select2Cascade($('#parentList'), $('#childList'), '/api/categories?parent_id=:parentId:'); cascadLoading.then( function(parent, child, items) { // Open the child listbox immediately child.select2('open'); // or Dump response data console.log(items); })
BTW, if you like this anyway, don’t forget to star the gist.
1 Comment