Search code examples
jsf-2primefaces

Setting OK(submit) button in JSF 2.0


I have a form and two command buttons. I want that on pressing the enter key, the second commandButton is pressed, but the first commandButton is being pressed.

Please consider the following sample code.

<h:form>
    <p:inputtext value="#{bean.mobileNumber}" />
    <p:commandButton id="startNewChat" value="Chat" action="#{bean.startNewChat}" update="chatWindow" />
    <br />
    <br />

    <p:outputPanel id="chatWindow">
        <p:inputTextarea readonly="true" value="#{bean.chatMessages}" />
        <p:inputText value="#{bean.newChatMessageFromWeb}" />
        <p:commandButton id="submitChatMessage" action="#{bean.submitChatMessage}" value="Send Message" />
    </p:outputPanel>

</h:form>

When Enter key is pressed, first commandButton(with id="startNewChat") is pressed, but I want that second commandButton(with id="submitChatMessage") should be pressed.

What I have tried: accesskey="13", type="submit", id="submit"


Solution

  • I assume that you want to apply this on the second input field, in that case you need to capture the keypress event and invoke the button by JS when the key code is 13.

    <form id="form">
        ...
        <p:inputText value="#{bean.newChatMessageFromWeb}" onkeypress="if (event.keyCode == 13) { document.getElementById('form:submitChatMessage').click(); return false; }" />
        <p:commandButton id="submitChatMessage" action="#{bean.submitChatMessage}" value="Send Message" />
    

    (note that I added an id to the <h:form> so that the command button gets a fixed ID which is selectable by JS, also note the return false, this will block the default button from getting fired)

    A more clean way would be to put each form in its own <h:form>.

    <h:form>
        <p:inputtext value="#{bean.mobileNumber}" />
        <p:commandButton id="startNewChat" value="Chat" action="#{bean.startNewChat}" update=":chatWindow" />
    </h:form>
    
    <p:outputPanel id="chatWindow">
        <h:form>
            <p:inputTextarea readonly="true" value="#{bean.chatMessages}" />
            <p:inputText value="#{bean.newChatMessageFromWeb}" />
            <p:commandButton id="submitChatMessage" action="#{bean.submitChatMessage}" value="Send Message" />
        </h:form>
    </p:outputPanel>