Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - How to update a value displayed in the page without refreshing

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)?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...