drop down not retaining selected value after post back

此生再无相见时 提交于 2019-12-04 04:27:39

问题


I'm using classic asp, I have a drop down list that the user selects and then presses submit. After they press submit the drop down list is going back to the default value instead of what they selected. Is there anyway to keep the state of the drop down between post backs instead of it going back to the default? Can post code sample if needed. Thanks!


回答1:


You have to "select it" serverside according to the values that the user has POSTed.

<select id="cars">
  <option value="volvo" 
      <%
      if request.form("cars") = "volvo" then 
          response.write("selected") 
      end if %>
      >Volvo</option>
  <option value="Saab" 
      <%
      if request.form("cars") = "Saab" then 
          response.write("selected") 
      end if %>
      >Saab</option>
  <option value="Mercedes" 
      <%
      if request.form("cars") = "Mercedes" then 
          response.write("selected") 
      end if %>
      >Mercedes</option>
  <option value="Audi" <%
      if request.form("cars") = "Audi" then 
          response.write("selected") 
      end if %>
      >Audi</option>
</select>

Of course, you might want to homegrown your own function to avoid all that boilerplate.

<% 
sub option(value, data, select_id) 
    Response.Write("<option value=""" & value & """)
    if request.form(select_id) = value then 
        Response.Write("selected") 
    end if
    Response.Write(">" & data & "</option>")
end sub
%>
' (...)
<select id="cars">
    <% option("volvo", "Volvo", "cars") %>
    <% option("Saab", "Saab", "cars") %>
    <% option("Mercedes", "Mercedes", "cars") %>
    <% option("Audi", "Audi", "cars") %>
</select>

If you pass the function a blank select_id, it will not care about trying to select the selected item of the select on postback.




回答2:


You can use javascript and plain HTML to achieve this: HTML: create a hidden field

Javascript: On submit keep the selected value in hidden variable

On page load loop thru the drop down values and set the selected value using the hidden variable

One more variant is available in http://www.daniweb.com/forums/thread105485.html



来源:https://stackoverflow.com/questions/2487783/drop-down-not-retaining-selected-value-after-post-back

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