您可以使用 jQuery 轻松完成此操作。看看这些选择器:
在prop() 函数上。
现在进入重点:
为了更好地处理 ids 元素,请在 form 包装 p:selectOneRadios 上使用 prependId="false"。
您不想重新加载页面,所以在p:commandButton 中使用ajax="true"。
<p:commandButton value="select" ajax="true" onclick="selectRadios()" update="@form"/>
如果您为p:selectOneRadio 指定id,primefaces 将在呈现的HTML 页面中将其用作input type="radio" 的name 属性。当然,如果你不在form 元素上使用prependId="false",primefaces 会将forms id 添加到无线电name attr.,所以它看起来像name="formId:radio1"。 prependId="false" 是 name="radio1"。
现在,当您知道您的单选按钮具有特定的 name 时,您可以选择 first 此name 指定的每个组的第一个,功能很简单:
function selectRadios(){
jQuery('input[name=radio1]:first').prop('checked', true);
jQuery('input[name=radio2]:first').prop('checked', true);
};
所以整个代码看起来像这样:
<script type="text/javascript">
function selectRadios(){
jQuery('input[name=radio1]:first').prop('checked', true);
jQuery('input[name=radio2]:first').prop('checked', true);
};
</script>
<h:form id="formID" prependId="false">
<p:selectOneRadio id="radio1" value="#{testBean.radio1}">
<f:selectItem itemLabel="Wide" itemValue="1" />
<f:selectItem itemLabel="No Ball" itemValue="2" />
<f:selectItem itemLabel="Normal" itemValue="3" />
</p:selectOneRadio>
<p:selectOneRadio id="radio2" value="#{testBean.radio2}">
<f:selectItem itemLabel="1" itemValue="1" />
<f:selectItem itemLabel="2" itemValue="2" />
<f:selectItem itemLabel="3" itemValue="3" />
</p:selectOneRadio>
<p:commandButton value="select" ajax="true" onclick="selectRadios()" update="@form"/>
</h:form>
注意:如果您不想通过update="radio1 radio2"更新整个form,也可以单独更新每个p:selectOneRadio
编辑
我不知道如何在primefaces(使用主题时)中选择radio button而不创建request,因为在点击radio button之后GET @987654356将创建@,其中将获得相关的UI图标(至少对于第一次点击)。如果您对此感到满意,请继续阅读。
既然您不想制作经典的HTTP request 或AJAX request,请更改您的commandButton 的类型:
<p:commandButton type="button" value="Default select" id="selButtonId" onclick="selectRadios();" />
并使用此js 函数触发点击radio button:
function selectRadios(){
jQuery('[for=radio1\\:0]').click();
jQuery('[for=radio2\\:0]').click();
};
ID of radio button 将用作 label + :x ,其中 x 是 button 的实际订单号。 (0 是第一个)。
这是使用click()函数的正确方法,因为你想点击label而不是按钮本身,解释here。
注意: Primefaces 3.1.1 版与不支持button 元素的refresh method 的jQuery 1.6.x 版捆绑在一起(从1.8 版开始支持)。否则你可以使用:
function selectRadios(){
jQuery('input[name=radio1]:first').prop('checked', true).button("refresh");
jQuery('input[name=radio2]:first').prop('checked', true).button("refresh");
};
所以恕我直言,上面写的就是你在你的情况下所能做的。我不知道button refresh 方法是否有其他替代方法。如果我错了,肯定会有人纠正我。
问候