Binding Dynamic Text Fields Created By Javascript To Bean
i have the following code, this creates the number of textfields that i enter inside the textField.
Solution 1:
You can better approach this with a backing bean than using Javascript. Using ajax you wouldn't need any page refreshes. Something along the lines of this:
HTML
<h:form>
<p>
<h:inputText value="#{bean.noOfFields}" />
<h:commandButton value="Create fields">
<f:ajax execute="@form" render="@form" />
</h:commandButton>
</p>
<hr />
<p>
<c:forEach items=#{bean.values} varStatus="counter">
Field no. #{counter.index} <h:inputText value="#{bean.values[counter.index}" /><br />
</c:forEach>
<h:commandButton action="#{bean.submit}" value="Save" />
</p>
</h:form>
Bean.java
@ManagedBean
@ViewScoped
public class Bean {
private String noOfFields = 1;
private String[] values = new String[1];
public void submit() {
// save values in database
}
public String getNoOfFields() {
return noOfFields;
}
public void setNoOfFields(String noOfFields) {
try {
values = new String[Integer.valueOf(noOfFields)];
this.noOfFields = noOfFields;
catch(NumberFormatException ex) {
values = new String[1];
noOfFields = "1";
}
}
public String[] getValues() {
return values;
}
}
Note
In case you want to stick to a keyup event, you can easily bind this to <h:inputText value="#{bean.noOfFields}" />
too. Though I'd recommend not doing this, since every keystroke will invoke another ajax call.
Post a Comment for "Binding Dynamic Text Fields Created By Javascript To Bean"