How to update the value displayed on the page without updating

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 bean support with these attributes:

public class NewOfferSupportController {

   private String val1;
   private String val2;
   private String result;

//Get set methods...


I want the outputText element to automatically change its value when some values ​​are inserted into val1 and val2 fields without refreshing the page. The result variable should be calculated this way (it calculates the percentage): (val1 * val2) / 100

Can you give me a hand to resolve some of my doubts ?:

I know I need something like javascript or AJAX for this. What do you think is the best way to do this?

I love to know how can I do this with AJAX, can you please give me some advice?

Since I need fields of type String, how should my validation be implemented?

Can I just avoid characters that are not numbers to enter in fields (If the key pressed is not a number, it is not shown in the input field at all)?


source to share

2 answers

If this is a simple calculation that doesn't require a server call, then you should go with a client side javascript solution

But how do you like doing it using Ajax here you go.

You can use the <f:ajax>

and attribute render

to make this thing happen using AJAX.

      <h:inputText value="#{managedBean.val1}" > 
         <f:ajax event="keyup" render="result" listener="#{managedBean.someThingToDoListener}"/> 
      <h:inputText value="#{managedBean.val2}" > 
        <f:ajax event="keyup" render="result" listener="#{managedBean.someThingToDoListener}"/> 

      <h:outputText id="result" value="#{managedBean.result}"/>


@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



If you are using java then get JQuery. After you've processed and got the desired output with your code, you can simply grab the dom element you want to place it in and do something like this:





All Articles