我能找到的最接近的副本是:Exclude field from a form in JSF。但是,它没有说明如何使用 JavaScript 来做到这一点。
正如 Kukeltje 已经指出的那样,我不会选择客户端解决方案。使用 Ajax 可以获得相同的结果。作为示例,我创建了一个表单,其中在选中复选框时提交值 1。如果未选中复选框,则将提交值 2。
<h:form>
<h:panelGrid columns="3">
<h:outputLabel for="check" value="Check"/>
<h:selectBooleanCheckbox id="check" value="#{myBean.checked}">
<f:ajax event="change" render="submit"/>
</h:selectBooleanCheckbox>
<h:message for="check"/>
<h:outputLabel for="value1" value="Value 1"/>
<h:inputText id="value1" value="#{myBean.value1}" required="true"/>
<h:message for="value1"/>
<h:outputLabel for="value2" value="Value 2"/>
<h:inputText id="value2" value="#{myBean.value2}" required="true"/>
<h:message for="value2"/>
<h:commandButton id="submit" value="Submit">
<f:ajax execute="#{myBean.execute()}" render="@form"/>
</h:commandButton>
</h:panelGrid>
</h:form>
提交规则的字段由命令按钮的<f:ajax execute="..." 属性控制。它应该包含一个或多个客户端 ID,以空格分隔。在本例中,值是在支持 bean 中创建的:
public String execute() {
return checked ? "value1" : "value2";
}
如您所见,它基于绑定到复选框的checked。如果选中value1,则应该执行,否则value2。
为了更新命令按钮的execute 属性,我在复选框中添加了<f:ajax event="change" render="submit"/> 以更新命令按钮(及其执行客户端ID)。
我已在字段中添加了必填项,以表明如果您将其中一个字段都留空,则会显示错误消息。
您可以使用输入字段的渲染属性获得相同的效果:
<h:form>
<h:panelGrid columns="3">
<h:outputLabel for="check" value="Check"/>
<h:selectBooleanCheckbox id="check" value="#{myBean.checked}">
<f:ajax event="change" render="@form"/>
</h:selectBooleanCheckbox>
<h:message for="check"/>
<h:outputLabel for="value1" value="Value 1"/>
<h:inputText id="value1" value="#{myBean.value1}" required="true"
disabled="#{not myBean.checked}"/>
<h:message for="value1"/>
<h:outputLabel for="value2" value="Value 2"/>
<h:inputText id="value2" value="#{myBean.value2}" required="true"
disabled="#{myBean.checked}"/>
<h:message for="value2"/>
<h:commandButton id="submit" value="Submit">
<f:ajax execute="@form" render="@form"/>
</h:commandButton>
</h:panelGrid>
</h:form>