在JSF表单中按Enter键时指定默认a4j:commandButton

时间:2013-12-12 09:28:04

标签: java javascript jsf richfaces

我的 JSF表格包含
多个 h:inputText多个 a4j:commandButton
此外
我有2个按钮(搜索)和(重置)

我在编辑任何press Enterh:inputText的需要 (搜索)按钮将被解雇

<h:form id="searchForm" onkeypress="formKeypress();">

    <h:panelGrid columns="4" >

        <h:outputText value="name" />
        <h:panelGroup>
            <h:inputText 
                title="name"
                value="#{myController.name}" >                          
            </h:inputText>
            <a4j:commandButton 
                title="name Detail"
                action="#{myController.nameDetail}" >               
            </a4j:commandButton>
        </h:panelGroup>

        <h:outputText value="city" />
        <h:panelGroup>
            <h:inputText 
                title="city"
                value="#{myController.city}" >                          
            </h:inputText>
            <a4j:commandButton 
                title="name Detail"
                action="#{myController.cityDetail}" >               
            </a4j:commandButton>
        </h:panelGroup>

    </h:panelGrid>


    <h:panelGrid >
        <h:panelGroup>
            <a4j:commandButton
                id="searchButton" 
                value="search" title="search"
                action="#{myController.search}"
                render="searchResultsGrid" />                       
        </h:panelGroup>
    </h:panelGrid>


    <f:verbatim>
        <script type="text/javascript" >
            <!--

            function formKeypress() {
            //  if (event.keyCode == 13) {
            //      document.getElementById('searchForm:searchButton').click();
            //      return false; 
            //  }
            }

            -->
        </script>
    </f:verbatim>       

</h:form>

问题在于 在编辑任何press Enter期间h:inputText时 表单中的第一个a4j:commandButton将被触发 不是(搜索)按钮

请注意
我检查了答案
Default action to execute when pressing enter in a form
但是h:commandButton的那个 我面临JavaScript错误异常

ReferenceError: event is not defined
[Break On This Error]
if (event.keyCode == 13) {

3 个答案:

答案 0 :(得分:6)

您必须将事件传递给JavaScript函数:

<h:form onkeypress="return formKeypress(event);"
        id="srch">
  <h:inputText />
  <h:commandButton id="no" value="NO!" action="#{bean.no}" />
  <h:commandButton id="yes" value="YES!" action="#{bean.yes}" />
</h:form>
<script type="text/javascript">
  var formKeypress = function(event) {
    if (event.keyCode === 13) {
      document.getElementById('srch:yes').click();
      return false;
    }
    return true;
  };
</script>

答案 1 :(得分:0)

您可以使用richfaces'Hotkey。使用您的示例:

<rich:hotKey selector="#searchButton" key="return">
    <rich:componentControl target="searchButton" operation="click" />
</rich:hotKey>

答案 2 :(得分:-1)

使用PrimeFaces组件:

<!-- Default button when pressing enter -->
<p:defaultCommand target="submit"/>

将它与焦点组件结合使用,你会摇滚!

<!-- Focus on first field, or first field with error -->
<p:focus context="feesboek"/>