提交后将值保留在for循环中

问题描述 投票:-1回答:1

如果表单提交不完整,我试图使用for循环选项保留我的select中的值。它将值插入到数据库中并且功能完全正常但我不希望人们在提交表单不完整时再次填写所有for循环选择。

if(!empty($_POST['height'])){
    $height = $_POST['height'];
}
<select class="form-control selectpicker" name="height">
    <option value="" disabled selected>Select Your Height</option>
        <?php
        for ($i=1; $i<=250; $i++)
        {?>
    <option value="<?php echo $i;?>"><?php echo $i;?>cm</option>
        <?php
        }
        ?>
</select>

我的其他选择功能完美:

<?php
if(isset($_POST['city'])){ 
$city = $_POST['city'];}?>
 <select class=" form-control selectpicker" name="city" value="">
  <optgroup label="Thailand">
   <option disabled selected>Select A City</option>
   <option
    <?php
    if (isset($city) && $city=="Bangkok") echo "selected";?>
    >Bangkok</option>
   <option <?php
    if (isset($city) && $city=="Phuket") echo "selected";?>
    >Phuket</option>
   <option <?php
    if (isset($city) && $city=="Pattaya") echo "selected";?>
    >Pattaya</option>
  </optgroup>
 </select>

基本上我想要实现与City选择相同的结果,但是在Height选择中使用for循环。

我花了最近几天的时间研究并尝试实现不同的代码和策略以使其工作,但我仍然无法使其正常运行。非常感谢任何帮助,如果需要更多代码或解释,我将很乐意提供。

php forms
1个回答
2
投票

你在$height增加了价值。但在select中,您没有使用它来保留选定的值。更改您的下拉高度,如下所示 -

if(!empty($_POST['height'])){
    $height = $_POST['height'];
}
<select class="form-control selectpicker" name="height">
    <option value="" disabled selected>Select Your Height</option>
        <?php
        for ($i=1; $i<=250; $i++)
        {?>
    <option value="<?php echo $i;?>" <?php if (isset($height) && $height==$i) echo "selected";?>><?php echo $i;?>cm</option>
        <?php
        }
        ?>
</select>
© www.soinside.com 2019 - 2024. All rights reserved.