[SalesForce] pressing enter on inputText does not trigger commandButton

<apex:form styleClass="container">  
<apex:actionRegion >  
  <div class="col-md-3 col-sm-5 col-xs-5 input-group">
    <apex:inputText value="{!searchString}" styleClass="form-control" html-placeholder="Search" />
    <span class="input-group-btn">
      <apex:commandButton  value="Go" action="{!Search}" rerender="searchResults" styleClass="btn btn-default"></apex:commandButton>
    </span>
  </div>
  <apex:pageBlock id="searchResults"> 
    <apex:pageBlockTable value="{!results}" var="a" id="tblResults" styleClass="table-gray col-md-6 col-sm-12 col-xs-12">
      <apex:column >
        <apex:facet name="header">
          <apex:outputPanel >Name</apex:outputPanel>
        </apex:facet>
        <apex:outputLink value="#" onClick="Javascript:parent.setValue('{!a.Name}','{!inputId}')">{!a.Name}</apex:outputLink>     
      </apex:column>
    </apex:pageBlockTable>
  </apex:pageBlock>
</apex:actionRegion>
</apex:form>

The problem is that when I type something into the inputText and press 'enter' it does not rerender or preform the action. How can I make it so that the user can press either 'Go' or press 'enter'?

Best Answer

Catch the enter-key at your inputText with the onkeypress-handler and trigger a fake-click on the button:

<script>
    function handlerKeyPress(ev) {
        if (window.event && window.event.keyCode == 13 || ev.which == 13) {
            $('.myUniqueSubmitButtonClass').click();   
            return false;
        } else {
            return true;
        }
    }
</script>
... 
<apex:inputText value="{!searchString}" onkeypress="return handlerKeyPress(event);" /> 
...
<apex:commandButton styleClass="myUniqueSubmitButtonClass btn btn-default" value="Go" action="{!Search}" rerender="searchResults" />

Note:

  • For the sake of simplicity I use here jquery. For sure you may rewrite it also without.
  • I added "myUniqueSubmitButtonClass" to be able to select to button easily
Related Topic