2014-01-29 14 views
0

我有一個選擇表單的網站,並試圖使其工作,以便在提交表單時,選擇表單保留用戶選擇的內容。我需要使用servlet或Javascript的JSP。以JSP或Javascript的形式保留用戶選擇

<form method="post" id="mainForm" name="mainForm"> 
<div> 
    <label style="margin-left: 10px;" for="specialty">Specialty:</label> 
    <select name="specialty"> 
     <option value="ob/gyn">OB/GYN</option> 
     <option value="surgeon">Surgeon</option> 
     <option value="heart surgeon">Heart Surgeon</option>    
     <option value="pediatrician">Pediatrician</option> 
     <option value="general physician">General Physician</option> 
    </select> 
</div> 
<div> 
    <label style="margin-left: 10px;" for="zipCode">ZIP Code:</label> 
    <input type="text" name="zipCode" value=<%=patient.getZip().substring(0, 5) %>> 
</div> 
<div> 
    <label style="margin-left: 10px;" for="range">Range From ZIP Code: </label> 
    <select name="range"> 
     <option value="5">Exact (Match all 5 digits)</option> 
     <option value="4">Match first 4 digits</option> 
     <option value="3">Match first 3 digits</option>   
     <option value="2">Match first 2 digits</option> 
     <option value="1">Far (Match only first digit)</option> 
    </select> 
</div> 
<input type="submit" name="findExpert" value="Find Expert" /> 

我會添加什麼,使這項工作?

回答

0

你可能想在這裏使用類似Struts的東西。但稍微難看,快速的方法來做到這一點是這樣(假設此JSP提交給自己,它看起來像它一樣):首先,開頭的表單標籤之前補充一點:

<% 
String specialty=request.getParameter("specialty"); 
String range=request.getParameter("range"); 
specialty=(specialty==null?"":specialty); // will be null if form not submitted yet 
range=(range==null?"":range); // will also be null if not submitted yet 
%> 

然後,取以您的第一個菜單爲例,對每個選項標籤執行此操作:

<option value="ob/gyn" <%=specialty.equals("ob/gyn")?"selected=\"selected\"":""%>>OB/GYN</option> 

這將起作用。有JavaScript解決方案也可以工作,但它們不會更容易實現。不過要注意的是:除非這個JSP只是爲了完成工作而一次性快速完成,否則最終會產生很多雜亂的代碼,除非你使用了一個框架(同樣,Struts是一種可能性),它處理了很多這樣的事情你的東西。