【问题标题】:How to set default value for drop-down/select in JSP?如何在 JSP 中设置下拉/选择的默认值?
【发布时间】:2012-04-24 14:12:09
【问题描述】:

我有一个字符串数组列表eqArray

我需要在我的 JSP 中使用以下内容的下拉列表中显示它:

<% 

    for(int count=0;count<eqArray.size();count++){ %>
            <option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>  
     <%} 
%>

我有一个 eqName 字符串,它是 eqArray 的一部分,默认情况下应该是选定的值。

如何在不必检查并将第一个选项始终设置为 eqName 的情况下进行操作?

【问题讨论】:

  • 如果不检查 eqName 条件,您将无法完成。

标签: java jsp select input options


【解决方案1】:

将数组中eqName元素的索引改为0,或者使用条件语句。

<% 
for(int count=0; count < eqArray.size(); count++){ %>
        <%if(eqArray.equals("eqName"){ %>           
            <option  selected="selected" value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>  
        <%} %> 
        <option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>  
 <%} %>

但使用 JSTL 标签库而不是使用 scriptlet。

【讨论】:

    【解决方案2】:
    <% for(int count=0; count<eqArray.size(); count++){ %>
        <option value="<%= eqArray.get(count) %>" <%= (eqArray.get(count).equals("eqName"))?"selected":"" %> ><%= eqArray.get(count) %></option>  
    <%} %>
    

    【讨论】:

      【解决方案3】:

      您可以通过 JQuery 来完成,恕我直言,它更干净:

      <select data-selected="${eqName}">
      <% 
          for(int count=0;count<eqArray.size();count++){ %>
                  <option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>  
           <%} 
      %>
      </select>
      

      在页面末尾:

      <script type="text/javascript">
        $("select[data-selected]").each(function() {
            var selected = $(this).data("selected");
            $("select[data-selected='" + selected + "'] option[value='" + selected + "']").attr("selected", "selected");
        })
      </script>
      

      这样,你只需要在你的每个页面中包含js即可。

      顺便说一句,我推荐你使用 JSTL 和 EL,这样更具可读性:

      <%@ page language="java" contentType="text/html; charset=UTF-8"
          pageEncoding="UTF-8"%>
      <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
      <select data-selected="${eqName}">
        <c:forEach items="${eqArray}" var="model">
          <option value="${model}">${model}</option>
        </c:forEach>
      </select>
      

      【讨论】:

        【解决方案4】:

        你可以通过两种方式实现这些

        • 使用jsp
        • " 选定="选定" >
        • 通过在选择框代码末尾使用Javascript

          document.getElementById('selectBoxID').value=""

          使用选择框id代替selectBoxID id

        【讨论】:

          猜你喜欢
          • 2021-01-13
          • 2021-08-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-25
          • 1970-01-01
          • 2012-09-13
          • 1970-01-01
          相关资源
          最近更新 更多