如何从下拉列表中选择选项标签? [英] How get selected option label from a dropdown list?
问题描述
我正在开发一个简单的Web应用程序,其中我想在下一个JSP页面的HTML页面中选择一个下拉列表的选项标签。我使用MVC模式,因此Servlet作为控制器将重定向(转发)请求到JSP视图。
I am developing a simple web application in which I want to take the option label of a dropdown list in HTML page on the next JSP page. I am using MVC pattern and thus Servlet as a controller will be redirecting (forwarding?) the request to JSP view.
request.getParameter )
给我只有选项值。但在我的情况下,期权价值和标签是不同的。如何获取选项标签?
The request.getParameter()
gives me only the option value. But in my case the option value and label are different. How can I get the option label?
推荐答案
您需要在服务器端维护选项值和标签的映射。例如。里面一些 ServletContextListener
或者servlet的 init()
:
You need to maintain a mapping of option values and labels in the server side. E.g. inside some ServletContextListener
or perhaps servlet's init()
:
Map<String, String> countries = new LinkedHashMap<String, String>();
countries.put("CW", "Curaçao");
countries.put("NL", "The Netherlands");
countries.put("US", "United States");
// ...
servletContext.setAttribute("countries", countries);
当您将其作为 $ {countries}
,那么你可以显示如下:
When you put it in the application scope as ${countries}
, then you can display it as follows:
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
这样您就可以在服务器端获取标签,如下所示:
This way you will be able to obtain the label in the server side as follows:
Map<String, String> countries = (Map<String, String>) getServletContext().getAttribute("countries");
// ...
String countryCode = request.getParameter("country");
String countryName = countries.get(countryCode);
// ...
或在JSP中显示纯文本:
Or to display plain in JSP:
<p>Country code: ${param.country}</p>
<p>Country name: ${countries[param.country]}</p>
或者预先选择下拉列表:
Or to pre-select the dropdown:
<select name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}" ${param.country == country.key ? 'selected' : ''}>${country.value}</option>
</c:forEach>
</select>
这篇关于如何从下拉列表中选择选项标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!