我能够通过php变量设置文本字段的值,以便刷新页面时,文本字段会像下面这样填充:
<td><input type="text" name="user" value="<?php echo ($_REQUEST['user']); ?>" /></td>
但是,我想对具有不同变量$gender
的单选按钮执行相同的操作。我该怎么办?
<td><input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other</td>
答案 0 :(得分:2)
<?php
'<td><input type="radio" name="gender" value="male" '.($_REQUEST['gender'] == "male" ? 'checked' : '').'> Male<br>
<input type="radio" name="gender" value="female" '.($_REQUEST['gender'] == "female" ? 'checked' : '').'> Female<br>
<input type="radio" name="gender" value="other" '.($_REQUEST['gender'] == "other" ? 'checked' : '').'> Other</td>'
?>
答案 1 :(得分:2)
如果要针对多个无线电组自动执行此操作,则可以编写一个函数:
<?php
declare (strict_types=1);
function radio_buttons(string $name, array $values_labels, int $indent = 4)
{
$ind = str_repeat(' ', $indent);
foreach ($values_labels as $value => $label)
{
$checked = ($_REQUEST[$name] ?? '') === $value ? ' checked' : '';
echo <<<__EOF__
$ind<input type="radio" id="radio-$name-$value" name="$name" value="$value"$checked><label for="radio-$name-$value">$label</label>
__EOF__;
}
}
?>
<body>
<form>
<?php radio_buttons('gender', ['male' => 'Male', 'female' => 'Female', 'other' => 'Other'], 4); ?>
<button type="submit">submit</button>
</form>
</body>