简体   繁体   中英

Option value doesn't match the right value

I have a $seasons variable that contains 21 seasons. For each season I want to make a option in html that you can select. If I press the submit button I want the option that is selected before submitting, is still selected. I try to do that with this code:

<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>

The problem is that the value of the option always jumps back to 21.

You need

selected="selected"

instead of

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>

It depends on your array type, but for a normal array:

 $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>

You made a mistake. I've rewritten your code:

<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>

Your "echo selected" call was outside of your if statement . In your case you selected all the options and your browser then shows the last selected, in your case option 21. Also your if statement itself was wrong.

I've rewritten you're code. It now checks if $_GET['season'] is set and if $_GET['season'] equals $season['season']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM