2013-05-01 65 views
1

我使用下面的代碼來處理HTML按鈕事件:HTML按鈕事件和選擇複選框

if(request.getParameter("btnSubmit")!=null) 

,我使用下面的代碼來捕捉選擇複選框有所有相同的名稱(「選擇」):

String[] selecttype = request.getParameterValues("choices"); 

if (selecttype != null && selecttype.length != 0) 
{ 
    for (int i = 0; i < selecttype.length; i++) 
    { 
    out.println("<h4><font color = 'red'>" + selecttype[i] + "</font></h4>"); 
     } 
} 

問題是,在按下按鈕提交之前,所選複選框的值會顯示在屏幕上。但是,按下提交按鈕時,這些值消失。任何幫助嗎?!

+0

這是一個Java Servlet嗎?你是否相應地將html [checked屬性](http://reference.sitepoint.com/html/input/checked)設置爲視圖中的'selecttype'值? – 2013-05-01 16:44:17

+0

@AnthonyAccioly jsp不是servlet。提交按鈕位於對同一頁面具有操作的表單之下。發生自動回覆時,所選複選框的值將消失! – 2013-05-01 16:56:03

回答

0

根據捕獲的選項(即勾選先前選定的複選框),您需要某種邏輯來在複選框中設置checked屬性。我建議你將表單提交給一個負責處理捕獲的選擇的中間Servlet,將它們存儲到比String數組更合適的數據結構中,並將請求轉發回您的jsp頁面,這也會使業務邏輯與視圖。

無論如何,如果你真的需要重新提交到同一頁面沒有中間的Servlet,這裏是一個偷懶的辦法來處理checked屬性:

<% 
    // Put this scriptet before your checkboxes 
    String[] choiceArray = request.getParameterValues("choices"); 
    // avoids NPEs 
    Set<String> capturedChoices = new HashSet<String>(); 
    if (choiceArray != null) { 
     capturedChoices = new HashSet<String>(Arrays.asList(choiceArray));  
    } 
%> 

而在你的複選框渲染代碼:

<input type="checkbox" name="choices" value="choice1" 
    <%= capturedChoices.contains("choice1") ? "checked=\"checked\"" : "" %> /> 

<input type="checkbox" name="choices" value="choice2" 
    <%= capturedChoices.contains("choice2") ? "checked=\"checked\"" : "" %> /> 

<!-- And so on (replace `choice1`, `choice2`, etc with actual values). --> 

當然,有比Set<String>(例如,boolean[]Map<String, Boolean>)更適合的數據結構來保存捕獲的選項,但是這應該讓您知道必須做什麼東北。