2015-10-02 32 views
0

我有一個PF的selectOneRadio來選擇要下載的文件類型。另外我有一個commandButton使用onclick屬性來調用一個下載servlet。問題是,當我選擇文件類型並單擊按鈕時,所選值當然還沒有提交。我正在尋找一些方法來獲得所選的值,當我點擊一個下載按鈕。獲取p:selectOneRadio值到JS函數

這裏是我的代碼:

<p:selectOneRadio id="sorType" value="#{bean.type}" layout="custom"> 
    <f:selectItem itemLabel="XML" itemValue="XML" /> 
    <f:selectItem itemLabel="XLS" itemValue="XLS" /> 
    <f:selectItem itemLabel="CSV" itemValue="CSV" /> 
</p:selectOneRadio> 

<p:commandButton type="button" ajax="false" onclick="return downloadFile('#{bean.type}');" /> 

回答

2

如果要檢查客戶端選擇的值,你將需要定義widgetVar屬性爲您p:selectOneRadio,例如:

<p:selectOneRadio widgetVar="widgetSorType" id="sorType" value="#{bean.type}" 
    layout="custom"> 

    <f:selectItem itemLabel="XML" itemValue="XML" /> 
    <f:selectItem itemLabel="XLS" itemValue="XLS" /> 
    <f:selectItem itemLabel="CSV" itemValue="CSV" /> 
</p:selectOneRadio> 

這將允許輕鬆找到元素 - 然後您可以進一步使用它來檢查實際選擇的值。我可以看到兩個選項如何做到這一點:

function getSelectedTypeVer1() { 
    return PF('widgetSorType').getJQ().find(':checked').val() || ""; 
} 

function getSelectedTypeVer2() { 
    var inputs = PF('widgetSorType').inputs; 

    for (var i = 0; i < inputs.length; i++) { 
     if (inputs[i].checked) { 
      return inputs[i].value; 
     } 
    } 

    return ""; 
} 

選擇哪個方式更適合你 - 既將返回選定的值或情況沒有一個空字符串已被選中。因此,所有剩下的工作就是調用它在你按鈕的onclick,因此,例如:

<p:commandButton type="button" ajax="false" 
    onclick="return downloadFile(getSelectedTypeVer1());" /> 

測試在PrimeFaces 5.2