0

I've the following form:

<h:form>
    <h:inputText size="2" value="#{orderMB.quantity}" />
    <h:outputLabel value=" #{orderMB.totalPriceOneItem} €" />
    <h:commandButton value="submit" />
</h:form>

And I've the following method in a session scoped managed bean:

public void setQuantity(int quantity) {
    this.quantity = quantity;
    setTotalPriceOneItem(quantity* item.getItem().getPrice().doubleValue());
}

I would like to auto-update the total price result on every key press of the input field. How can I achieve this without pressing the submit button?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

1 Answers1

2

Your code isn't doing that anywhere. It's missing a <f:ajax>.

<h:inputText size="2" value="#{orderMB.quantity}">
    <f:ajax event="keyup" render="total" />
</h:inputText>
<h:outputText id="total" value="#{orderMB.totalPriceOneItem} €" />

The event attribute can be set to any HTML DOM event on which JSF must submit the form by ajax, such as click, keyup, blur, focus, etc. The render attribute can be set to any JSF client ID which needs to be updated when the ajax submit finishes. In this case it's referring the ID of the component showing total price.

Note that I replaced the wrong <h:outputLabel> by <h:outputText>. Also noted should be that a setter isn't exactly the right place to perform business logic (a getter also not!). Better revert that setter method to a true setter and add an ajax listener method:

<f:ajax event="keyup" listener="#{orderMB.updateTotalPriceOneItem}" render="total" />
public void updateTotalPriceOneItem() {
    totalPriceOneItem = quantity * item.getItem().getPrice().doubleValue();
}

In case when it still doesn't work, then verify if you have a <h:head> in the template instead of a <head>. If still in vain, work through commandButton/commandLink/ajax action/listener method not invoked or input value not updated.


That said, I strongly recommend to take a pause and work through a sane JSF 2.x book. The above is usually already covered in the 1st chapter.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555