验证失败后如何保留HTML Select标签的用户输入?
问题修复方案
你的select标签无法保留用户输入的问题,根源在三个细节上:
- 变量名冲突:你把存储用户提交值的变量和选项数组都命名为
$type,导致用户的输入被数组覆盖。 - 选中判断逻辑错误:
$t == $type是拿单个选项字符串和整个数组比较,永远不会相等,自然不会有选项被标记为选中。 - 错误使用select属性:
<select>标签本身不支持value属性,选中状态完全靠<option>的selected属性控制,加了也无效。
修正后的select代码
<label>Brick Type: </label> <select name='type'> <?php // 单独存储用户提交的选择,避免和选项数组重名 $selected_type = $_POST['type'] ?? ''; // 选项数组换个名字区分 $types = ['', "A grade Red/Cream brick $2", "B grade Red/Cream brick $1.50", "Red/Cream clinkers $2.50"]; foreach ($types as $t){ // 拿单个选项和用户提交的值对比,匹配则添加selected属性 $select = ($t == $selected_type) ? 'selected' : ''; echo "<option value='$t' $select>$t</option>"; } ?> </select>
完整修正后的表单代码
<form action="index.php" method="post" novalidate="true"> <div class="box"><h1>Brick Order</h1></div> <fieldset> <label>Customer Name: <span class="error"> <?= $errors['cusName']??'';?> </span> </label> <input type='text' name='cusName' value="<?= $cusName??'';?>"/> <br> <label>Mobile: <span class='error'> <?= $errors["mobile"]??'';?> </span> </label> <input type='text' name='mobile' maxlength="10" value="<?= $mobile??'';?>"/> <br> <label>Preferred delivery date:</label> <input type='date' name='delivery' value="<?= $date??'';?>"/> <br> <label>Number of Bricks: <span class='error'> <?= $errors["num_bricks"]??'';?> </span> </label> <input type='number' name='num_bricks' value="<?= $num_bricks??'';?>"/> <br> <label>Brick Type: </label> <select name='type'> <?php $selected_type = $_POST['type'] ?? ''; $types = ['', "A grade Red/Cream brick $2", "B grade Red/Cream brick $1.50", "Red/Cream clinkers $2.50"]; foreach ($types as $t){ $select = ($t == $selected_type) ? 'selected' : ''; echo "<option value='$t' $select>$t</option>"; } ?> </select> <br> </fieldset> <button type="submit" name="submit">SEND</button> </form>
修改后,表单验证失败刷新页面时,就能正确保留用户之前选择的砖型了。
内容的提问来源于stack exchange,提问作者clappersk
相关产品推荐
相关产品推荐

