Loadeding/refreshing options of a select2 list box (using ajax) based on selection of another select2 list box.
Check the live demo.
Create a new instance of Select2Cascade
by passing the following 4 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
The response json should be a flat object of value:label pairs. e,g,
{
"20150415" : "Chittagong Zila",
"20190901" : "Comilla Zila",
"20221601" : "Cox's Bazar Zila",
"20301401" : "Feni Zila"
}
Otherwisw you have to adjust the way of populating child options (at line 29).
When #parentList
is changed, call to path/to/geocode/district/SELECTED-PARENT/zilla
and set the options of #childList
from the ajax response.
var options = { width: 'resolve' };
new Select2Cascade($('#district'), $('#zilla'), 'path/to/geocode/district/:parentId:/zilla', options);
new Select2Cascade($('#zilla'), $('#thana'), 'path/to/geocode/zilla/:parentId:/thana', options);
If you want to do something with the response data or selectboxes, you can set (any number of) callbacks to be executed after the child listbox refreshed -
var cascadLoading = new Select2Cascade($('#parent'), $('#child'), 'path/to/api/categories?parent_id=:parentId:');
cascadLoading.then( function(parent, child, items) {
// Open the child listbox immediately
child.select2('open');
// Dump response data
console.log(items);
})
Hello @L5eoneill ,
Definitely very good addition! 👍
I'll soon update the script and will add the callback for data processing functionality.
About using
{"id": val, "text": textval}
as default format, I'm not yet sure. The reason behind using{id: "textVal"}
was, it's generic output of most of the list APIs. So I didn't want people to make another, custom API only for feeding Select2 list boxes.