The closest of a duplicate I could find is: Exclude field from a form in JSF. However, it does not show how to do this using JavaScript.
As Kukeltje already pointed out, I would not go for a client side solution. You could get the same result using Ajax. As an example I created a form where value 1 is submitted when the checkbox is checked. If the checkbox is not checked, value 2 will be submitted.
<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 what fields to submit rule is controlled by the <f:ajax execute="..."
attribute of the command button. It should contain one or more client IDs, separated by a space. In this example the value is created in the backing bean:
public String execute() {
return checked ? "value1" : "value2";
}
As you can see it is based on checked
which is bound to the checkbox. If checked value1
should be executed, else value2
.
In order to update the command button's execute
attribute, I've added <f:ajax event="change" render="submit"/>
to the checkbox to update the command button (and its execute client IDs).
I have added required to the fields to show that an error message will be shown for one of the fields if you leave them both empty.
You could get the same effect using 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>