简体   繁体   English

如何在提交后选择下拉选项保持选中状态

[英]How to make selected drop down option stay selected after submit

I am trying to make the select box sticky that is located in the first foreach loop: 我正在尝试使位于第一个foreach循环中的选择框变粘:

I believe there should be an if statement located inside the <option> tag like below: 我相信应该有一个位于<option>标签内的if语句,如下所示:

if($selectedMake==$key){ 
  echo selected='selected';
}

echo "<option im not sure how to properly enter it in here?>$key</option>"

// Start of code below: //下面的代码开头:

$selectedMake = $_POST['make'];
$cars = array(
    'Toyota'=>array(
        'Corolla'=>array(
            'image'=>'corolla.png',
            'colour'=>'blue',
            'transmission'=>'manual',
            'doors'=>'2'
            ),
        'Highlander'=>array(
            'image'=>'highlander.png',
            'colour'=>'silver',
            'transmission'=>'auto',
            'doors'=>'4'
            ),
        ),

    'Mazda'=>array(
        'RX7'=>array(

            'colour'=>'blue',
            'transmission'=>'manual',
            'doors'=>'2'
            ),
        'MX-5'=>array(
            'colour'=>'red',
            'transmission'=>'manual',
            'doors'=>'2'
            )
        )


    );
echo '<form method="post" action="cars.php">';
echo '<select name="make">';
foreach ($cars as $key => $value) {

    echo "<option>$key</option>"; // This option tag needs to be made sticky

}

echo '</select>
<input type="submit" name="submit">
</form>
';

if (isset($_POST['submit'])) {

$selectedMake = $_POST['make'];

echo "<h1>$selectedMake</h1>";
foreach ($cars as $key => $value) {
    if ($selectedMake == $key) {
        foreach ($value as $key => $value) {
            echo "<b>$key</b> <br>";
        foreach ($value as $key => $value) {
            if ($key == 'image') {

                echo '<img src="imgs/'.$value.'" width="150px">';
            } else {
                echo "<li>$key: $value</li>";
            }

        }
    echo "<br>";
        }
    }
}
} else {
echo "Not clicked";
}



echo '<pre>',print_r($cars),'</pre>';

 ?>

如果是粘性的,则表示如果它与您拥有的值匹配则选择:

echo "<option".($selectedMake==$key ? " selected" : "").">$key</option>"

Ah, I think I know what you mean. 啊,我想我知道你的意思。 You want something like this... 你想要这样的东西......

<select name="make">
<?php
foreach (array_keys($cars) as $key) :
$selected = $key === $selectedMake ? ' selected' : '';
?>
    <option<?= $selected ?>><?= htmlspecialchars($key) ?></option>
<?php endforeach ?>
</select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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