Dynamic default selection for a drop down menu using url variables

大城市里の小女人 提交于 2019-12-12 02:06:40

问题


I have several links on one page which all direct to the same page, but each of them passes a different variable in the URL (http://sitename.com/thispage.php?id=3). I set new variables to true or false depending on which value is passed for "id", then put the true/false variables in to set the default option on an option tag like so:

    if (isset($_GET['id']))
        $id = ($_GET['id']);

    if ($id = 4)
        $id4 = true;
    else
        $id4 = false;

    ...

    <option value="Value" selected="<?php echo "$id4"; ?>">
        Value
     </option>

Excuse me if it seems messy.

I've got 12 of those setup, one for each menu option. I can't seem to get it to display the correct one as the default selection though, as it always selects the 2nd to last menu item.


回答1:


One thing you should correct is putting true and false in quotation marks, otherwise they will be converted from boolean to string and end up as a 1 or 0.

Or you could replace the whole thing with this

<option<?php if (isset($_GET['id']) && $_GET['id'] == 4){ echo ' selected'; } ?>>
    value
</option>


来源:https://stackoverflow.com/questions/7808402/dynamic-default-selection-for-a-drop-down-menu-using-url-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!