Xajax 0.2: Tips and Tricks: select/option tags
Xajax 0.2: Tips and Tricks: select/option tags
[edit] General Information
Here are a few tips for working with select and options tags.
- Always remember to declare an ID and a NAME attribute for form elements
- Remember, by default xajax.getFormValues will only return the option(s) that are selected.
- See this thread for information on alternative ways to pass select value(s)
<select id="foobar" name="foobar">
<option value="15">foo</option>
<option value="11">bar</option>
</select>
From your PHP script, you can change the selected option using either of the following two methods:
// xajax 0.2.x syntax
$objResponse->addAssign("foobar","selectedIndex","1");
// or
$objResponse->addAssign("foobar", "value", "11");
In the first case, setting the selectedIndex gives you the ability to select an option regardless of its value. By using a zero based index value, you can select the option without knowing the corresponding value attribute.
In the second case, you can select an option by its value attribute.
Both of the example assigns will cause "bar" to be selected.
[edit] Chained Selects
Often we want to load one select based on the value selected in a previous select control. Here is an example of how that might work:
(html)
<select id='master' name='master' onchange='xajax_setSlave(xajax.$("master").value);'>
<option value=1>option 1
<option value=2>option 2
</select>
<span id='slave_placeholder'>
<select id='slave' name='slave'>
</select>
</span>
(php)
function setSlave($master) {
$objResponse = new xajaxResponse();
$options = array();
switch ($master) {
case 1:
$options['1.1'] = "1.1 test option";
$options['1.2'] = "1.2 test option";
break;
case 2:
$options['2.1'] = "2.1 test option";
$options['2.2'] = "2.2 test option";
$options['2.3'] = "2.3 test option";
break;
}
$output = "<select id='slave' name='slave'>";
foreach ($options as $option => $text) {
$output .= "<option value='".$option."'>{$text}");
}
$output .= "</select>";
// xajax 0.5 syntax shown, for prior versions use addAssign
$objResponse->assign('slave_placeholder', 'innerHTML', $output);
return $objResponse;
}
$xajax->registerFunction("setSlave");
In the real world, the initial html code would probably be populated with options from the server side script (read from a database or config file); but for this example, hard coded values will have to suffice.
Another example of this can be found here.