Loadeding/refreshing options of a select2 list box using ajax based on selection of another select2 list box.
Create a new instance of Select2Cascade by passing the following 4 things -
- Parent select2 listbox
- Child select2 listbox
- URL to load child items on selection changed
- Optional data object to be sent with request. The selected value of parent select2 listbox will be set in this data object as
parent_id
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"
}When #parentList is changed, call to /path/to/geocode?type=district&parent_id=SELECTED-PARENT
and set the options of #childList from the ajax response.
new Select2Cascade($('#district'), $('#zila'), 'path/to/geocode', {type:"zila", parent_id: ''});
new Select2Cascade($('#zila'), $('#thana'), 'path/to/geocode', {type:"thana", parent_id: ''});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/geocode', {type:"child", parent_id: ''});
cascadLoading.then( function(parent, child, items) {
// Open the child listbox immediately
child.select2('open');
// Dump response data
console.log(items);
})
a simple modification to support select2 options (as theme)