Can h:inputText invoke a method inside managed bean when I press the return/enter key

As per your question history, I know that you're using JSF 2.0, so here's a JSF 2.0 targeted answer: use <f:ajax> which listens on a change event and use keypress event to invoke it when the enter key is pressed (keycode 13).

<h:inputText value="#{bean.text1}" 
    onkeypress="if (event.keyCode == 13) { onchange(); return false; }">
    <f:ajax event="change" listener="#{bean.listener}" />
</h:inputText>

The #{bean.listener} should point to a method like

public void listener(AjaxBehaviorEvent event) {
    // ...
}

The easiest way is to put the inputText in a form and hide a commandButton next to it.

For example:

<h:form>
  <h:inputText styleClass="myText" value="#{myBean.text}"/>
  <h:commandButton styleClass="myButton" action="#{myBean.myMethod}" style="display:none;" value="submit"/>
</h:form>

UPDATE:

If you are using Seam you can use the <s:defaultAction/> tag. This makes that commandButton that contains it the one that responds to the ENTER.

<h:commandButton class="myButton" action="#{myBean.myMethod}" style="display:none;" value="submit">
  <s:defaultAction/>
</h:commandButton>

If you aren't using Seam you could try one of the similar defaultAction controls

Or you could roll your own with a bit of Javascript; ideally jQuery. For example:

$('input.myText').keypress(function(e) {
    if (e.which == 13) {
        $('.myButton').click();
    }
});

Actually you can use the following syntax:

<h:inputText value="#{bean.text1}" 
     onkeypress="return (event.keyCode == 13)">
  <f:ajax event="keypress" listener="#{bean.listener}" />
</h:inputText>

JSF creates an event chain and whatever you state under "onkeypress" will be evaluated BEFORE your f:ajax event. Thus you can return false to break the event chain. If you use the change event on f:ajax it'll of course fire on other change events which you probably don't want.

Tags:

Jquery

Jsf