How get selected option label from a dropdown list

2019-03-22 04:56发布

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?

2条回答
倾城 Initia
2楼-- · 2019-03-22 05:37

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>
查看更多
地球回转人心会变
3楼-- · 2019-03-22 05:48

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>
查看更多
登录 后发表回答