Search code examples
jsfrichfaces

Call an action listener via ajax when user presses enter on a h:form input field


I have this form

<h:form id="formId" prependId="false">
    Descrizione <h:inputTextvalue="#{bean.description}" />
    Prezzo: <h:inputText value="#{optionalManaged.price}" />
    <a4j:commandLink styleClass="button smallButton" actionListener="#{bean.method}"
                     execute="formId" render="otherDiv">
        +
    </a4j:commandLink>

</h:form>

At the moment, pressing the a4j:commandLink stores the two input filelds' values inside my bean and calls my action listener correctly.

What I'd like to happen is that pressing enter on the second inputText does the same.

I made a naive try by calling the a4j:commandLink click() via jquery from inside the inputText. This, obviously, didn't work.

Any idea on how I could do this?


Solution

  • You need to detect if Enter key was pressed and click the command link programmatically. Just don't forget to set its id, as well as id of input component. The piece of JavaScript you need to add when the page has finished loading is:

    document.getElementById('input').onkeypress = function(e) {
        var event = e || window.event;
        var code = event.which || event.keyCode;
        if (code == 13) {
            document.getElementById('link').click();
            return false;
        }
    }