Version 7

    By default forms are submitted when you press the Enter/Return key from within an input type text field if it's the only input field in the form.

    This is not always the desired behaviour as we sometimes want to force form submittion on a button click for example.

    This example shows how we can add simple JavaScript event listener code which looks for Enter/Return key and how to use it to prevent form submitting.

     

     

     

     

    • First we have our javascript code:

     

    <script type="text/javascript">
    //<![CDATA[
    function checkEnter(e){
      var characterCode
    
      if(e && e.which){
        e = e
        characterCode = e.which
      }
      else{
        e = event
        characterCode = e.keyCode
      }
    
      if(characterCode == 13){  
         return false
      }
      else{  
         return true
      }
    }
    //\]\]\>
    </script>
    

     

     

    • And in our facelet/jsp we have:

     

    <h:form>
       <h:inputText id="myId" value="#{myBean.someValue}" onkeypress="return checkEnter(event);"></h:inputText>
       <h:commandButton action="#{myBean.submitAction}" value="Submit"></h:commandButton>
    </h:form>
    

     

    Pressing the Enter/Return key now while within the input field will not submit the form.