简体   繁体   English

如何根据值更改下拉菜单的选定值

[英]How to change the selected value of the dropdown based on the value

I have a requirement where the user will fill out and submit a form. 我有一个要求用户将填写并提交表格的地方。 If there are any errors found on the server side, the same form will be displayed to the user, but now the previously selected value of the drop down is not selected by default again. 如果在服务器端发现任何错误,则将向用户显示相同的表单,但是现在默认情况下不会再次选择下拉菜单的先前选择的值。 I want the default selected value of the drop down to be based the value the user selected before. 我希望下拉菜单的默认选择值基于用户之前选择的值。

在服务器上创建下拉列表的代码应检查在打印选项时,如果选项与用户选择的选项匹配,则标记为“已选择”

You're going to some how have to maintain state between page refreshes. 您将了解一些如何在页面刷新之间保持状态。

For example, you could store the value in a cookie while the user is filling out the form, and when the page refreshes (with errors) you can check for the value and deal with it accordingly. 例如,您可以在用户填写表单时将值存储在cookie中,并且当页面刷新(有错误)时,您可以检查该值并进行相应处理。

which server side language you are using? 您正在使用哪种服务器端语言? this is not looking the JavaScript problem, because after submitting the page get refreshed and you are validating on server side, so you can use POST Global vars to return the value Or you can ask me with more information 这不是JavaScript问题,因为提交页面后刷新,并且您正在服务器端进行验证,因此可以使用POST Global vars返回值,也可以向我询问更多信息

To ensure that the default selected value is always the previously selected one, you could catch the selected value on the server-side script that receives the form. 为确保默认选择的值始终是先前选择的值,您可以在接收表单的服务器端脚本中捕获选择的值。 Then, save this value to a session variable and compare it later with this (inside the loop that creates the dropdown) : 然后,将此值保存到一个会话变量中,然后将其与此进行比较(在创建下拉列表的循环中):

if (isset($_SESSION["previousValue"])) {
    if ($value == $_SESSION["previousValue"]) {
        echo '<option value="$value" selected="selected">$value</option>';
    } else {
        echo '<option value="$value">$value</option>';
    }
}

Hope this helps you 希望这对您有帮助

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

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