使用 JSTL 为 JSP 下拉列表选择的值 [英] Selected value for JSP drop down using JSTL

查看:24
本文介绍了使用 JSTL 为 JSP 下拉列表选择的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Servlet 中有 SortedMap 来填充 JSP 中的下拉值,我有以下代码

I have SortedMap in Servlet to populate drop down values in JSP and I have the following code

    SortedMap<String, String> dept = findDepartment();
    request.setAttribute("dept ", dept);

在 JSP 中

       <select name="department">
          <c:forEach var="item" items="${dept}">
            <option value="${item.key}">${item.value}</option>
          </c:forEach>
        </select>

我使用一个 JSP 页面进行插入和更新.当我编辑页面时,如何将选定的值设置为下拉选择的值将来自数据库的位置.

I am using one JSP page for insert and update. When I am editing the page how can I set selected value to drop down where selected value will come from database.

推荐答案

在 HTML 中,选中的选项由 上的 selected 属性表示代码>元素像这样:

In HTML, the selected option is represented by the presence of the selected attribute on the <option> element like so:

<option ... selected>...</option>

或者,如果您是 HTML/XHTML 严格的:

Or if you're HTML/XHTML strict:

<option ... selected="selected">...</option>

因此,您只需要让 JSP/EL 有条件地打印即可.前提是您已按如下方式准备所选部门:

Thus, you just have to let JSP/EL print it conditionally. Provided that you've prepared the selected department as follows:

request.setAttribute("selectedDept", selectedDept);

那么应该这样做:

<select name="department">
    <c:forEach var="item" items="${dept}">
        <option value="${item.key}" ${item.key == selectedDept ? 'selected="selected"' : ''}>${item.value}</option>
    </c:forEach>
</select>

另见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆