[SalesForce] Preventing default form submission and calling an action instead

I have a VF Page that initially shows only an input field (lookup), with other parts of the page not rendered. When the user enters a value and tabs out of the field, the onchange event calls my controller (via actionSupport); during the rerender, other parts of the page are conditionally rendered based on the input value.
Here's part of my VF page:

<apex:actionRegion >
  <apex:outputPanel id="SalesOrderLookup"> 
    <apex:pageBlockSection title="Sales Order Information" id="SalesOrderInfo">
      <apex:inputField taborderhint="5" value="{!PropertyAccount.Sales_Order__c}">
        <apex:actionSupport event="onchange" 
                            action="{!checkSalesOrderAccount}" 
                            reRender="SalesOrderLookup" />
      </apex:inputField>

This is working perfectly… if the user tabs out of the field, thus firing the onchange event. However, if the user simply presses return after keying in a value (which is likely, given that it's the only control on the page at this point), the whole page is being submitted. This results in a whole-page refresh instead of a reRender, and the action ({!checkSalesOrderAccount}) never runs. I'd like the following behavior:

  • When the user presses enter, the form is not submitted.
  • When the user presses enter, the {!checkSalesOrderAccount} action is called.

Note that there is no submit button on the page, but I assume that pressing enter is firing the form's submit action? Which leads me to one more requirement/constraint: all of this code is part of an <apex:component> which is shared by a couple of pages; the <apex:form> tag is in the containing page, not in the component, so I can't use the form's onsubmit, even if it would work for the return key.

I'm considering an onkeypress event handler on the inputField to watch for return being pressed. It could cancel the keypress (which I think would prevent the submit), and even call {!checkSalesOrderAccount} if I swap my actionSupport for actionFunction. But I wonder if there's a better way to do this.

Best Answer

You can use a simple javascript function to prevent a standard submitting the form with enter key and execute an apex:actionFunction instead:

<apex:form id="orderSearchForm" onkeyup="submitListener(event)">

<apex:actionFunction name="onFormSubmit" 
                     action="{!checkSalesOrderAccount}" 
                     reRender="SalesOrderLookup" />

<script>
function submitListener(e){
    var keynum = 0;
    if (window.event){
        keynum = window.event.keyCode;
    }
    else if (e.which){
        keynum = e.which;
    }

    // Here we check whether the Enter button was pressed
    if (keynum == 13){
        onFormSubmit();
    }
}
</script>