我有一个表单和两个命令按钮。我希望在按下回车键时,第二个 commandButton 被按下,但第一个 commandButton 被按下。

请考虑以下示例代码。

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

当按下 Enter 键时,第一个 commandButton(with id="startNewChat") 被按下,但我想要第二个 commandButton(with id="submitChatMessage") 应该被按下。

我试过的: accesskey="13", type="submit", id="submit"

最佳答案

我假设您想将其应用于第二个输入字段,在这种情况下,您需要捕获按键事件并在键代码为 13 时通过 JS 调用按钮。

<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" />

(请注意,我在 id 中添加了 <h:form> 以便命令按钮获得可由 JS 选择的固定 ID,还要注意 return false ,这将阻止默认按钮被触发)

更简洁的方法是将每个表单放在自己的 <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>

10-07 13:03
查看更多