简体   繁体   English

在中选择所选选项的简单方法 <select>从$ _POST给定的值?

[英]Simple way to select chosen option in <select> from the value given by $_POST?

如何在发送的$_POST数据的HTML <select>输入的选项中添加selected="selected"位,而在每个选项中不使用if语句?

<?php

$options = array(1 => 'Banana', 2 => 'Apple');

foreach ($options as $key => $value) {
    echo '<option value=""';
    if ($key == $_POST['fruit']) echo ' selected="selected"';
    echo '>'.$value.'</option>';
}

?>

Programatically, you could do it like this: 在编程上,您可以这样:

$optionNames = array('This', 'Is', 'A', 'Test');
echo '<select id="testselect" name="testselect">';
foreach($optionNames as $currentOption) {
    echo '<option value="'.$currentOption.'"';
    echo $_POST['testselect'] == $currentOption ? ' selected="selected"' : '';
    echo '>'.$currentOption.'</option>';
}
echo '</select>';

Must confess I don't have a dev box up at the moment to test the above code, but it should be OK. 必须承认我目前没有开发箱可以测试上面的代码,但是应该没问题。 (Apologies if not.) :-) (如果没有,抱歉。):-)

I suppose using an if statement for each option is most efficient. 我想对每个选项使用if语句是最有效的。

But you can create an array containing empty strings except for the location of the option you want to select in order to eliminate the if statement. 但是您可以创建一个包含空字符串的数组,除了要选择的选项的位置以消除if语句之外。

$options = array(1 => 'Banana', 2 => 'Apple', 3 => 'Orange');
$selected_options = array_fill(1, sizeof($options), "");
if(array_key_exists($_POST['fruit'], $options))
    $selected_options[$_POST['fruit']] = " selected=\"selected\"";

echo '<select id="fruit" name="fruit">';
foreach($options as $optionId => $optionText)
    echo '<option value="'.$optionId.'"'.$selected_options[$optionId].'>'.$optionText.'</option>';
echo '</select>';

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

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