Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
989 views
in Technique[技术] by (71.8m points)

jsf - required attribute of inputText should depend on submitted value of another component

I have a form which contains a dropdown and two input fields.

<h:selectOneMenu />
<h:inputText />
<h:inputText />

I would like to make the required attribute of the input fields conditional depending on the selected value of the dropdown. If the user chooses the first item of the dropdown, then the input fields must be required. If the user chooses the second item, then those would not be required.

How can I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just bind the dropdown to the view and directly check its value in the required attribute.

<h:selectOneMenu binding="#{menu}" value="#{bean.item}">
    <f:selectItem itemValue="first" itemLabel="First item" />
    <f:selectItem itemValue="second" itemLabel="Second item" />
</h:selectOneMenu>

<h:inputText value="#{bean.input1}" required="#{menu.value eq 'first'}" />
<h:inputText value="#{bean.input2}" required="#{menu.value eq 'first'}" />

Note that the binding example is as-is. Do absolutely not set it to a bean property here. See also How does the 'binding' attribute work in JSF? When and how should it be used?

Also note that the ordering of the components is significant. If the menu is located below the inputs in the tree, use #{menu.submittedValue eq 'first'} instead. Or if you want to be independent from that, use #{param[menu.clientId] eq 'first'} instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...