Create Dependent Dropdowns with Xajax
Create Dependent Dropdowns with Xajax
A very useful and intuitive type of form element is the dependent dropdown set. This consists of a linked pair or group of<select>tags whose contents are dependent on each other. For instance, you may have a list of food groups, and when you choose a specific food group, such as 'Fruit', another list gets populated with values such as 'Apple', 'Orange', 'Banana'. But if you choose 'Dairy', the second list will instead contain values like 'Milk', 'Cheese', 'Butter'.
Drawing on the example at [1], I made some changes and improvements. I will prrovide code snippets and explanation below.
[edit] Javascript Functions
First, you need a couple of standard Javascript functions. You need one to delete all the options from the list, and you need another one to add the options with data given to it by an Xajax function. Here are my two Javascript functions. Explanation is provided via comments.
// Truncate the option array of the select box
function delOptions(selectId) {
document.getElementById(selectId).options.length=0;
}
// Add a value to the option array. val corresponds to the "value" property of the <option>.
//"txt" corresponds to the way the option will appear in the list.
function addOption(selectId, val, txt) {
if((val == 0) || (txt == 0)) {
val = '';
txt = '';
}
var objOption = new Option(txt, val);
document.getElementById(selectId).options.add(objOption);
}
[edit] Assumptions about Data Format
In my example, I am using arrays in the form of:
array {
array[0] {
[value] => foo,
[txt] => bar
}
array[1] {
[value] => foo,
[txt] => bar
}
...
...
array[n] {
[value] => foo,
[txt] => bar
}
}
If your data is presented differently, you will need to tweak the Xajax functions that follow.
[edit] xajax Function
Our xajax function will basically parse the array and then send its data to the Javascript functions.
function createOptions($sSelectId, $options) {
global $objResponse;
$objResponse->script("document.getElementById('".$sSelectId."').length=1");
// Clear all the options from the list
$objResponse->script("delOptions('".$sSelectId."');");
// Add a blank option to the top of the list
$objResponse->script("addOption('".$sSelectId."', 0, 0);");
foreach ($options as $option) {
$objResponse->script("addOption('".$sSelectId."','".$option['value']."','".$option['txt']."');");
}
return $objResponse;
}