How get selected option label from a dropdown list?

好久不见. 提交于 2019-12-12 07:38:36

问题


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.

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?


回答1:


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);

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);
// ...

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>



回答2:


This can be done without storing anything on server side.

<select name="menu" id="menu">
<option value="1">label 1</option>
<option value="2">label 2</option>
</select>

<button onclick='show()'>Click me</button>

<script type="text/javascript">
function show(){
var theContents = document.getElementById('menu')[document.getElementById('menu').selectedIndex].innerText;
window.alert(theContents);
}
</script>


来源:https://stackoverflow.com/questions/8840655/how-get-selected-option-label-from-a-dropdown-list

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