PHP:默认情况下在选择框中显示“选定值”

时间:2013-04-08 12:28:59

标签: php

我的表单上有一个select框来搜索城市中的商店。假设它们是城市1,城市2,城市3等。当我选择城市3并单击搜索时,数据被发布并且商店正确显示。但是选择框仍然将城市1显示为默认值。这让用户感到困惑!

如果我搜索了City 3,重新加载页面后,选择框应该将City 3显示为“Selected value”而不是选择框的第一个值。

我该怎么办?请帮帮我。

3 个答案:

答案 0 :(得分:2)

只需阅读所选城市框的值并将其存储在变量中即可。例如: -

$selectedCity = $_POST['city'];

然后使用此$ selectedCity检查是否在您提交表单时选中了选中此框的选项:

   <?php if ($selectedCity == 'City1") { ?> "selected=selected" <?php }?>

答案 1 :(得分:0)

<option name="" selected></option>

对于您默认选择的那个,就像那样容易。

答案 2 :(得分:0)

以下是如何完成的简单示例:

<?php
//======================================================== 
// Get the company names
//========================================================
$selectQuery = mysql_query("SELECT `name`, `id` FROM " . TABLE_INFO_COMPANY);
while($selectContent = mysql_fetch_assoc($selectQuery)) 
    if($_POST['id' = $selectedContent['id'])
        echo '<option value="', $selectContent['id'], '" selected="selected">', $selectContent['name'], '</option>';
    else if($_POST['id' = $selectedContent['id'])
        echo '<option value="', $selectContent['id'], '">', $selectContent['name'], '</option>';
?>

在选择框中输入预选答案的正确方法是使用 selected =“selected”

相关问题