我有这个表单,有10个下拉选项可供选择,最后一个复选框免责声明在底部。
因此,例如,如果用户选择了所有10个答案并忘记检查底部的免责声明框并单击“提交”,则表单将返回错误消息,表明他们不同意免责声明,但所有答案都是之前选择的已经消失,他们将不得不重新做到这一点。我试图找到一种最佳实践方法来处理这个问题而不重复这么多代码...
我有什么工作,但这是多余的,特别是如果我有100个问题。
<select name="question1" id="question1">
<?php if ($question[0] == '0') {
$first = 'selected="selected"';
$second = '';
$third = '';
$fourth = '';
} elseif ($question[0] == '1') {
$first = '';
$second = 'selected="selected"';
$third = '';
$fourth = '';
} elseif ($question[0] == '2') {
$first = '';
$second = '';
$third = 'selected="selected"';
$forth = '';
} elseif ($question[0] == '3') {
$first = '';
$second = '';
$third = '';
$forth = 'selected="selected"';
}
?>
<option value="0" <?php echo $first; ?>>Answer 1</option>
<option value="1" <?php echo $second; ?>>Answer 2</option>
<option value="2" <?php echo $third; ?>>Answer 3</option>
<option value="3" <?php echo $fourth; ?>>Answer 4</option>
</select>
这仅适用于1个问题,因此您可以想象我将不得不重复所有问题。必须有更好的方法来做到这一点吗?
...谢谢
答案 0 :(得分:3)
<option value="0" <?= ($question[0] == 0 ? "selected='selected'" : ""); ?>>Answer 1</option>
<option value="1" <?= ($question[0] == 1 ? "selected='selected'" : ""); ?>>Answer 1</option>
<option value="2" <?= ($question[0] == 2 ? "selected='selected'" : ""); ?>>Answer 1</option>
<option value="3" <?= ($question[0] == 3 ? "selected='selected'" : ""); ?>>Answer 1</option>
通常 是如何完成的。
答案 1 :(得分:0)
据我所知,没有优雅的解决方案。我倾向于使用条件语句,例如;
<option value="0" <?=($question[0] == 0 ? ' selected' : '')?>>Answer 1</option>
答案 2 :(得分:0)
我是这样做的:
$array_existing_values = array(3,5);
$array_options = array(1,2,3,4,5);
foreach(array_options as $value)
{
$sel = null;
if (in_array($array_existing_values,$array_options)
{
$sel = ' selected ';
}
$html_options .= "<option value='$value' $sel>$value</option>";
}
为季节添加验证。
答案 3 :(得分:0)
试试这个。让$questions
像这样为用户提出所有问题:
$questions = array(
// The first question
array(
'question' => 'The 1st question?'
'answers' => array(
'answer 1',
'answer 2',
'answer 3',
'answer 4',
)
),
// The second question
array(
...
),
// etc
);
$answer
包含用户的所有答案,如下所示:
$answer = array(1, 2, 3, 2, ... );
然后你可以像这样重写所有问题:
foreach ($questions as $index => $question)
{
echo "<p>" . $question['question'] ."</p>\n";
echo "<select name='question" . $index . "' id='question" . $index . "'>\n";
foreach ($question['answers'] as $value => $answer)
{
echo "<option value='" . $value . "' " . ($value == $answer[$index] ? "selected='true'" : "") . ">" . $answer . "</option>\n";
}
echo "</select>";
}