2011-04-17 76 views
1

我想在複選框被選中時啓用輸入字段。此外,我想做一個服務器端驗證的文本字段,填充,如果複選框被選中,問題我面對的是,當我檢查多個並提交表單的空值該字段然後在servlet中進行驗證並將結果返回給用戶以填充輸入,其中一個檢查字段被檢查,另一個不是,即使我使用param來提高穩定性,我也不知道是什麼原因!JSP:某些表單字段穩定,而其他表單字段不穩定!

這裏的HTML代碼

<div class="groupElement"> 

    <input type="checkbox" name="communicationWay" id="communicationWay2" value="emailOption" ${param.communicationWay == 'emailOption'?'checked':'' } onchange="chgtx('email','communicationWay2')"/> 
    <label>Email</label> 


    <input class="inpClass" id="email" type="text" name="emailComm" value="${param.emailComm}" disabled/> 

</div> 

<div class="groupElement"> 

    <input type ="checkbox" name="communicationWay" id="communicationWay" value="cellPhoneOption" ${param.communicationWay == 'cellPhoneOption'?'checked':''} onchange="chgtx('cellPhone','communicationWay')" /> 
    <label> Cell phone number</label> 

    <input class="inpClass" id="cellPhone" type ="text" name="cellPhoneNoComm" value="${param.cellPhoneNoComm}" disabled /> 

    </div> 

和這裏的,啓用和禁用輸入字段

function chgtx(field, checkbox) { 

      var myField = document.getElementById(field); 
      var checkBtton = document.getElementById(checkbox); 
      myField.disabled= !checkBtton.checked; 

     } 

回答

2

你的複選框元素具有相同的名稱之間觸發Java腳本功能。所以在服務器端,您必須使用request.getParameterValues()來獲取所有選中的值。

String[] communicationWays = request.getParameterValues("communicationWay"); 
// ... 

當您使用request.getParameter(),如${param}是幹什麼的,只有一個值將被退回,這是該組中的第一個。您可以使用${paramValues}來獲取EL中的所有值。

但是,使用EL中的${paramValues}來設置checked狀態並不十分微不足道。有兩種方法來解決這個問題:

  1. 創建自定義EL函數確實像

    ${util:contains(paramValues.communicationWays, 'emailOption') ? 'checked' : ''} 
    ${util:contains(paramValues.communicationWays, 'phoneOption') ? 'checked' : ''} 
    

    public static boolean contains(Object[] array, Object value) { 
        Arrays.sort(array); 
        return Arrays.binarySearch(array, value) > -1; 
    } 
    
  2. 創建servlet的一個Map<String, Boolean>,並用它來代替在EL。

    Map<String, Boolean> communicationWays = new HashMap<String, Boolean>(); 
    request.setAttribute("communicationWays", communicationWays); 
    
    for (String communicationWay : request.getParameterValues("communicationWay")) { 
        communicationWays.put(communicationWay, true); 
    } 
    

    ${communicationWays.emailOption ? 'checked' : ''} 
    ${communicationWays.phoneOption ? 'checked' : ''} 
    
+0

@BlausC,我做了第二個選項,它的工作原理,許多感謝名單。但關於第一種方法,我應該在哪裏定義contains方法? – palAlaa 2011-04-17 21:16:25

+1

如何定義和配置自定義EL函數的例子在這個答案的底部附近提到:http://stackoverflow.com/questions/2523430/hidden-features-of-jsp-servlet/2525995#2525995 – BalusC 2011-04-17 22:30:23

+0

@blausC,您是否有任何建議讓文本輸入字段的禁用功能僅在頁面加載時第一次起作用,因爲如果我提交表單並從servlet返回,則會檢查檢查字段的位置,因爲字段已禁用! 如何在頁面第二次加載時啓用它? – palAlaa 2011-04-17 23:08:26