Preselecting Radio Buttons
if (isset($_POST['groupname']) &&
$_POST['groupname'] == 'php5') {
echo 'checked="checked" ';
}
|
A group of radio buttons is identified by the common name attribute. Out of a group of buttons, only one can be selected (or none). When submitting a form to the server, the value attribute of the selected radio buttons is transmitted to the server. Therefore, it is quite messy but rather trivial to prefill a group of radio buttons: Just compare the value in $_GET/$_POST with the associated value. If it fits, print out checked, the HTML attribute that preselects a radio button, as shown in the code.
Prefilling Radio Buttons (radio.php; excerpt)
<input type="radio" name="groupname" value="php3"
<?php
if (isset($_POST['groupname']) && $_POST
['groupname'] == 'php3') {
echo 'checked="checked" ';
}
?>/>PHP 3
<input type="radio" name="groupname" value="php4"
<?php
if (isset($_POST['groupname']) &&
$_POST['groupname'] == 'php4') {
echo 'checked="checked" ';
}
?>/>PHP 4
<input type="radio" name="groupname" value="php5"
<?php
if (isset($_POST['groupname']) &&
$_POST['groupname'] == 'php5') {
echo 'checked="checked" ';
}
?>/>PHP 5
This code can be extended so that a radio button is preselected when the user has previously saved his selection in a cookie, using the include file getFormData.inc.php, as shown in the following code.
Prefilling Radio Buttons (radio-cookie.php; excerpt)
<?php
require_once 'getFormData.inc.php';
?>
...
<input type="radio" name="groupname" value="php3"
<?php
if (getFormDataPOST('groupname') == 'php3') {
echo 'checked="checked" ';
}
?>/>PHP 3
<input type="radio" name="groupname" value="php4"
<?php
if (getFormDataPOST('groupname') == 'php4') {
echo 'checked="checked" ';
}
?>/>PHP 4
<input type="radio" name="groupname" value="php5"
<?php
if (getFormDataPOST('groupname') == 'php5') {
echo 'checked="checked" ';
}
?>/>PHP 5
|