简体   繁体   English

如何自动选择带有会话值的下拉框

[英]How to Auto Select Drop Down Box With Session value

        <select>
        <?php  foreach($result as $city) { ?>
        <option value="<?php echo $city->city_name; ?>" <?php if( strtolower($this->session->city) == strtolower($city->city_name)  ) { echo "selected"; }  ?>
        > <?php  echo $city->city_name; ?>  </option>
        <?php   } ?>
        </select>

Hi i am trying to auto select drop down box with the help of session but i am not able to select please some one help me out how could i auto select drop down box. 嗨,我正在尝试借助会话自动选择下拉框,但我无法选择,请有人帮助我如何自动选择下拉框。

First of all. 首先。 You should always provide the whole code, eg. 您应该始终提供完整的代码,例如。 in format of PHPFiddle. 以PHPFiddle的格式。

Secondly, you should not mix HTML and PHP. 其次,您不应混合使用HTML和PHP。

Also your problem cannot be deciphered from your question, because there might be several reasons. 同样,您的问题也无法从您的问题中解译出来,因为可能有多种原因。 Like the city name could be in uppercase or capitalized in your session variable. 就像城市名称可以是大写字母,也可以在会话变量中使用大写字母。

Your session variable might not be initialized with your session in the class constructor. 您的会话变量可能未在类构造函数中用您的会话初始化。

Also you might even not have a class at all, so the reference to $this would be obsolete. 另外,您甚至可能根本没有类,因此对$ this的引用将作废。

But those aside, here's a code that might help you: 除了这些,下面的代码可能会帮助您:

<?php
class MockSession {
    function __construct() {
    }
}
class Foo {

function __construct() {
    $this->session = new MockSession();
    $this->session->city = "Helsinki";
}
function printSelect() {
    $result = array("London","New York","Helsinki");

    echo '<select>';
    foreach ($result as $city) {
        $sel = '';
        echo $city." ".$this->session->city;
        if (strtolower($city)==strtolower($this->session->city)) {
        $sel = ' selected="selected" ';
        }
        echo '<option value="'.$city.'" '.$sel.'>'.$city.'</option>';
    }
echo '</select>';
}

}

$foo = new Foo();
$foo->printSelect();
?>

If you got value of your session on the page then you have to just modify your code as selected="selected" . 如果您在页面上获得了有价值的会话,则只需将代码修改为selected="selected" See updated code: 查看更新的代码:

<select>
    <?php
        foreach ($result as $city) {
    ?>
        <option
            value="<?php echo $city->city_name; ?>"
            <?php if (strtolower($this->session->city) == strtolower($city->city_name)) {
                echo 'selected="selected"';
            }
            ?>> 
            <?php echo $city->city_name; ?>
        </option>
    <?php 
        }
    ?>
</select>

But you should have to confirm first that you got value of $this->session->city . 但是,您必须首先确认您具有$this->session->city

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

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