Reputation: 12413
I have this 3 fields in a JSF page
<h:inputText id="val1" value="#{managedBean.val1}"/>
<h:inputText id="val2" value="#{managedBean.val2}"/>
<h:outputText value="#{managedBean.result}"/>
And i also have a backing bean with this attributes:
@ManagedBean
@RequestScoped
public class NewOfferSupportController {
private String val1;
private String val2;
private String result;
//Get set methods...
}
I want the outputText element to change its value automatically when some values are inserted in the fields val1 and val2 without the page being refreshed. The result variable should be calculated this way(It is calculating a percentage): (val1 * val2) /100
Can you give me a hand solving some of my doubts?:
I know that for doing this i need something like javascript or AJAX.What do you think should be the best way to do it?
Id love to know how could i do it with AJAX, could you give me some tips?
Since i need the fields to be of type String, how will my validation should be implemented?
Can i just avoid characters that are not digits to be typed in the fields(If the pressed key is not a number, don't appear at all in the input field)?
Upvotes: 2
Views: 10417
Reputation: 240860
If this is simple calculation, which doesn't need server call then you should go with client side javascript solution
But As you love to do it using Ajax here you go..
You can use <f:ajax>
and render
attribute to make this thing happen using AJAX .
<h:form>
<h:inputText value="#{managedBean.val1}" >
<f:ajax event="keyup" render="result" listener="#{managedBean.someThingToDoListener}"/>
</h:inputText>
<h:inputText value="#{managedBean.val2}" >
<f:ajax event="keyup" render="result" listener="#{managedBean.someThingToDoListener}"/>
</h:inputText>
<h:outputText id="result" value="#{managedBean.result}"/>
</h:form>
@ManagedBean(name = "managedBean")
public class Bean {
private String val1; // getter and setter
private String val2; // getter and setter
private String res; // getter and setter
...
public void someThingToDoListener(AjaxBehaviorEvent event) {
//res = some processing
}
}
See Also
Upvotes: 4
Reputation: 3123
If you're using java, then get JQuery. Once you have processed and gotten a desired result with your code, you could just grab the dom element you want to place it in and do something like so:
$("#result").html(newData);
Upvotes: 1