I couldn't find an exact duplicate, but a similar question is addressed in this Stack Overflow thread. The provided solution does not involve using JavaScript.
Instead of opting for a client-side approach as Kukeltje suggested, consider achieving the same outcome with Ajax. For instance, you can create a form where submitting value 1 depends on whether a checkbox is checked or not.
<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>
The logic of which fields to submit is determined by the <f:ajax execute="..."
attribute of the command button, which should contain one or more client IDs separated by spaces. In this scenario, the value is dictated by the backing bean:
public String execute() {
return checked ? "value1" : "value2";
}
This decision is based on the value of checked
, linked to the checkbox. If checked, value1
will be executed; otherwise, value2
.
To update the command button's execute
attribute, I utilized
<f:ajax event="change" render="submit"/>
for the checkbox to trigger the update of the command button (and its execute client IDs).
Including the 'required' attribute in the fields demonstrates that an error message will display if both are left empty.
Achieving a similar effect by utilizing the 'rendered' attribute of the input fields:
<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>