选项值与正确值不匹配

时间:2019-04-05 12:06:30

标签: php html select option selected

我有一个$seasons变量,包含21个季节。对于每个季节,我都希望在html中做出一个可以选择的选项。如果我按下提交按钮,则仍要选择在提交之前选择的选项。我尝试使用以下代码来做到这一点:

<select name="season" id="season" class="filter-season">
          <option value="all">-- Alle seizoenen --</option>
          <?php foreach($seasons as $season): ?>
          <option <?php if (isset($_GET['season']) == $season['season']){?> selected = "true" <?php }; echo "selected" ?>\value="<?php echo $season['season'] ?>"><?php echo $season['season']; ?></option>
          <?php endforeach; ?>
 </select>

问题在于该选项的值始终跳回到21。

3 个答案:

答案 0 :(得分:3)

您需要

selected="selected"

代替

selected=true

<select name="season" id="season" class="filter-season">
<option value="all">-- Alle seizoenen --</option>
<?php foreach($seasons as $season): ?>
<?php
$isSelected = (isset($_GET['season']) && $_GET['season'] == $season['season']) ? 'selected="selected"' : '';
?>
<option <?php echo $isSelected;?> value="<?php echo $season['season'] ?>"><?php echo $season['season'];?></option>
<?php endforeach; ?>
</select>

答案 1 :(得分:1)

这取决于您的数组类型,但对于普通数组:

 $seasons = [
     'winter',
     'summer'
 ];
 $selected_season = isset($_GET['season']) ? $_GET['season'] : false;


 <select name="season" id="season" class="filter-season">
     <option value="all">Alle seizoenen</option>
     <?php foreach($seasons as $season): ?>
         <option value="<?= $season; ?>" <?php $season == $selected_season ? 'selected="selected"' : ''?>><?= $season; ?></option>
     <?php endforeach; ?>
 </select>

答案 2 :(得分:0)

您犯了一个错误。 我已经重写了您的代码:

<select name="season" id="season" class="filter-season">
    <option value="all">-- Alle seizoenen --</option>
    <?php foreach($seasons as $season): ?>
        <option <?php if (isset($_GET['season']) &&  $_GET['season'] == $season['season']) echo "selected" ?> value="<?php echo $season['season'] ?>"><?php echo $season['season']; ?></option>
    <?php endforeach; ?>
</select>

您的“已选择回声” 通话不在您的 if声明之外。在您的情况下,您选择了所有选项,然后浏览器显示了最后一个选择,在情况选项中为21。而且您的 if语句本身是错误的。

我已经重写了您的代码。现在,它检查是否设置了$_GET['season'],并且$_GET['season']是否等于$season['season']