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

时间:2014-10-01 06:19:14

标签: php

我正在尝试使第一个foreach循环中的选择框变粘:

我认为if标记内应该有<option>语句,如下所示:

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

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

//下面的代码开头:     

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

 ?>

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

啊,我想我知道你的意思。你想要这样的东西......

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