当前位置: 动力学知识库 > 问答 > 编程问答 >

php - How to put selected on one particular option inside a foreach loop

问题描述:

I am trying to echo out "selected" on a value inside my array, within a foreach. If the form is false and my customer has already entered a particular value in my select, return it so he doesn't fill it again! That's what I am trying to do...

<?php

$marques = array('Word','Word1','Word20','Word46','Word9797');

foreach ($marques as $marque => $value)

{

if (isset($_POST['marque']) && $_POST['marque'] == $value[$_POST['marque']]) {

echo '<option value="'.$_POST["marque"].'">'.$value[$_POST["marque"]].'</option>';

}

echo '<option value="'.$marque.'">'.$value.'</option>';

}

?>

网友答案:
<?php
$marques = array('Word', 'Word1', 'Word20', 'Word46', 'Word9797');

foreach ($marques as $marque) 
   echo '<option value="'.$marque.'" '.(($marque == $_POST['marque']) ? 'selected' : '').'>'.$marque.'</option>';
?>
网友答案:

You mean this?

<?php
    $marques = array('Word','Word1','Word20','Word46','Word9797');

    foreach ($marques as $marque => $value) {
        $setItSelected = '';
        if (isset($_POST['marque']) && $_POST['marque'] == $marque) {
            $setItSelected = 'selected';
        }

        echo '<option value="'.$marque.'" '.$setItSelected.'>'.$value.'</option>';
    }
?>
网友答案:

Changing what's inside the value attribute doesn't make the item more or less selected. You need to add the selected attribute, see http://www.w3schools.com/tags/att_option_selected.asp

The output:ed html should look something like:

<option value="id" selected>some text</option>
网友答案:
<?php
 $marques = array('Word','Word1','Word20','Word46','Word9797');
        foreach ($marques as $marque) 
        {
        if (isset($_POST['marque']) && $_POST['marque'] == $marque') 
            echo '<option value="'.$marque.'" selected>'.$marque.'</option>';

        else
             echo '<option value="'.$marque.'">'.$marque.'</option>'; 
        }
    ?>

Your Array is one dimension, you can't use "=>" For select option you must add the "selected" attribute too at your option tag

分享给朋友:
您可能感兴趣的文章:
随机阅读: