Saturday, August 16, 2014

IE does not allows first time pressing enter key as submit using jQuery

If there is an input box in the form and a button to initiate the form submission, on clicking enter on the input box the form is not submitted automatically.
<form id="myForm">
   <input id="inputText" type="text"/>
   <input type="submit" id="submitButton" value="Submit" />   
</form>

So when the text is entered and enter key is pressed the form is not automatically submitted. However this works fine other browsers.
To fix that, we have to capture the key press event and act accordingly
<script type="text/javascript">
   $(document).ready(function(){
   $(function(){
      $("#inputText").keydown(function(e){
            if (e.keyCode == 13) {
               $("#submitButton").click();
               return false;
               }
            });
       });
    });
</script>
However submission of form with clicking of button in this way does not apply validation rules on the form. If validations should also be fired than do the script as follows
<script type="text/javascript">
   $(document).ready(function(){
   $(function(){
      $("#inputText").keydown(function(e){
            if (e.keyCode == 13) {
               if( !$("#myForm").valid()){
                   return false;
                  }
               $("#submitButton").click();
               return false;
               }
            });
       });
    });
</script>

No comments:

Post a Comment