2012-04-12 181 views
4

我有一個字符串陣列列表eqArray如何在JSP中設置下拉/選擇的默認值?

我需要證明它在一個下拉列表,我正在用我的JSP如下:

<% 

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

我有一個eqName串,該部分的eqArray並且應該是默認選定的值。

我該如何解決這個問題,而不必檢查並將第一個選項設置爲eqName?

+0

你不能沒有檢查的eqName條件完成。 – Phani 2012-04-12 08:49:32

回答

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

將數組中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 taglibs而不是使用scriptlets。

2

您可以通過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> 
0

您可以通過兩種方式

  • 實現這些使用JSP
  • 「選擇= 「selected」>
  • 通過在選擇框代碼末尾使用Javascript代碼

    的document.getElementById( 'selectBoxID')。價值= 「」

    代替selectBoxID ID使用選擇框ID

相關問題